Consider this Java code
class A{
//@returns Class object this method is contained in
// should be A in this case
public Class<?> f() {
return getClass();
}
}
class B extends A {}
B b = new B();
System.out.println(b.f());
//output -- B.class (Wrong, should be A.class)
inside f() i can't use getClass() because that will give me the runtype, which is B. I'm looking for a way to get the Class object of the class f() is inside (Without mentioning A explicitly, obviously)
new Object() {}.getClass().getEnclosingClass(). But please don't!
You can use exception stack trace facility to do something like this:
public String f() {
Exception E = new Exception();
E.fillInStackTrace();
return E.getStackTrace()[0].getClassName(); // load it if you need to return class
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With