Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Get Class object for containing class, Not Runtime Class

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)

like image 402
Mike Avatar asked Jul 09 '26 11:07

Mike


2 Answers

new Object() {}.getClass().getEnclosingClass(). But please don't!

like image 183
Tom Hawtin - tackline Avatar answered Jul 12 '26 00:07

Tom Hawtin - tackline


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
}
like image 38
ChssPly76 Avatar answered Jul 12 '26 02:07

ChssPly76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!