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
)
source to share
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.
source to share