In java it is possible to access the class without using (in other words typing) the name of the class. An example
public class Example {
/**
* Non static context, can only be called from an instance.
*/
public void accessClass() {
System.out.println(this.getClass());
}
}
However in a static context there is no similar method but only the .class static field. This question is focused in accessing the .class from within the java class itself, not from other classes.
public class Example2 {
//field used to demonstrate what is meant by "indirectly referencing the class name.
private static Class<Example2> otherClass = Example2.class;
private static int intField = 1;
/**
* Non static context, can only be called from an instance.
*/
public static void accessClass() {
// The .class static field can be accessed by using the name of the class
System.out.println(Example2.class);
// However the following is wrong
// System.out.println(class);
// Accessing static fields is in general possible
System.out.println(intField);
// Accessing a static field of the same Class is also possible, but does not satisfy the answer since the class name has been written in the declaration of the field and thus indirectly referenced.
System.out.println(otherClass);
}
}
Is there a way to access the .class
object of a class from a static context of the same class without referencing the class name (neither directly nor indirectly)?
Another restriction is that the answer is not allowed to instantiate the class or use the .getClass()
instance method.
I have created some examples above that try to demonstrate my findings.
I was surprised to notice that I could not find a way to access the .class
field without typing the class name from within the same class.
Is this just a side-effect of some design decisions, a or is there any fundamental reason that accessing .class
is not possible without the class name?
Revisiting this question, I add an oneliner that achieves the same result. The MethodHandles class
of utilities returns the Class<?>
in a single line, with a relatively good performance. This is easier to memorize, read and copy-paste around. These properties are useful in cases like creating loggers.
final Class<?> clazz = MethodHandles.lookup().lookupClass();
For a performance benchmark comparison see here the answer by Artyom Krivolapov