Java, Get a class object for a class, not a 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 cannot use getClass()

because that will give me a runtype type which is B

. I'm looking for a way to get an object Class

object Class

f()

inside (without explicitly mentioning it A

)

+2


source to share


5 answers


You can use the exception stack trace tool 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
}

      

+4


source


new Object() {}.getClass().getEnclosingClass()

... But please don't!



+6


source


I would have to say that it would be much simpler and clearer to just return A.class as @mmyers suggested. There is no point in trying to get it at runtime unless you really want the runtime value. The only problem that comes up is refactoring the class name and another with the same name exists in the same package.

I would take this opportunity for clarity in the code.

+2


source


you can use

class.getMethod("f",parameterTypes).getDeclaringClass()

      

+1


source


I know you said that you don't want to explicitly specify A.class

class A {        
    public Class<?> f() {
        return A.class;
    }   
}

      

but I am trying my best to find a use case where the above code is not satisfactory.

+1


source







All Articles