From the Java tutorial:
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending "
.class
"; for example,String.class
. This refers to the object (of typeClass
) that represents the type itself.
To what type of variable can this literal be assigned to?
Please give a small example if possible.
The literal itself is
MyClass
. If you writeMyClass.class
you get a Reference to the class object. If you writenew MyClass()
, it uses the literal to get you an instance of the class object you get byMyClass.class
. From the instance you get the same class object by callingmyClassInstance.getClass()
.I am not 100% sure, but the literal itself cannot be assigned to any variable. What you can do is getting the name of the class as string and use the reflection framework to create an instance.
Thanks to the other good answers here, you know what it is, but here's a typical usage example that may clarify also:
As the code suggests, this is a line where we're initialising a logging framework (in this example, I'm using the
org.apache.log4j
package, but the principle extends to other frameworks). ThegetLogger()
method requires a class literal so it knows what it's logging (i.e. the current object's class).When the JVM loads your application classes, it stores them as
java.class.Class
objects.So, there are usually several instances of type
Class
in memory that represents your classes. So you can do something like this:According to the JLS
Some common uses may be found in Class Literals as Runtime-Type Tokens.
Check out the Javadoc for
java.lang.Class
to see what you can do with one of these little guys - mostly related to reflection