What is a class literal in Java?

Class<String> c = String.class;

Check out the Javadoc for java.lang.Class to see what you can do with one of these little guys - mostly related to reflection


To understand that, you have to understand that String is an instance (object) of the class Class. A string literal (e.g. "I am a string.") is a notation which represents an instance (object) of the class String, whereas a class literal (e.g. Hashtable.class) is a notation which represents an instance of the class Class.


Thanks to the other good answers here, you know what it is, but here's a typical usage example that may clarify also:

    private static Logger log = Logger.getLogger(YourClassHere.class);

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). The getLogger() method requires a class literal so it knows what it's logging (i.e. the current object's class).


According to the Java Language Specification (JLS):

15.8.2 Class Literals

A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a . and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.