63

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 type Class) that represents the type itself.

To what type of variable can this literal be assigned to?

Please give a small example if possible.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
gameover
  • 11,813
  • 16
  • 59
  • 70

10 Answers10

54
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

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
44

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.

shinkou
  • 5,138
  • 1
  • 22
  • 32
  • 2
    @shinkou String is an instance (object) of the class Class. How come? It should be "String.class is an instance (object) of the class Class" right? – Ani Aug 04 '15 at 20:16
  • @Ani String itself is also an instance of the class Class which is assigned the class literal String.class. Think of `String str = "I am a string";`, where `str` is assigned a String literal "I am a string". – shinkou Nov 16 '15 at 17:15
  • 14
    `String` itself is NOT an instance of class `Class`. It has a literal, `String.class`, that is an instance of `Class`. If it was an instance of type `Class`, then `String.class` would be an instance of `Class`. `String` is not an instance of anything. – Lew Bloch Dec 01 '16 at 22:37
  • 1
    @LewBloch I omitted the `.class` to try to make things easier to understand. A class literal can't do anything without its type afterall. – shinkou Jan 13 '17 at 17:43
  • 6
    @shinkou, whatever the motivation, incorrect statements do not "make things easier to understand". _Au contraire_, they engender misunderstanding and confusion. Don't spread untruth. – Lew Bloch Jan 13 '17 at 20:05
  • @shinkou, it made things clear for me, thanks :) – phi1.614 May 11 '22 at 22:28
27

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).

Ben
  • 7,548
  • 31
  • 45
17

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
stacker
  • 68,052
  • 28
  • 140
  • 210
6

Some common uses may be found in Class Literals as Runtime-Type Tokens. The approach is widely used to implement the observer pattern, as seen in the EventListenerList, discussed here. The Converter application includes an example in ConverterRangeModel.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
5

The literal itself is MyClass. If you write MyClass.class you get a Reference to the class object. If you write new MyClass(), it uses the literal to get you an instance of the class object you get by MyClass.class. From the instance you get the same class object by calling myClassInstance.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.

bertolami
  • 2,896
  • 2
  • 24
  • 41
  • Sure you can. If not, you would not be able to pass it as a parameter to a function. The type of the literal is Class which can be assigned to references of that type. – jbruni Feb 26 '15 at 18:01
  • 2
    The literal itself is not the class name. Per https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.2 the class literal is the token `class`. From the JLS: "A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class." Note that it is not the name of the class, but the name followed by `.class`. – Lew Bloch Dec 01 '16 at 22:38
3

In examples it is someting like that:

Class myClass = MyClass.class

or

MyClass.class.getResourceAsStream("config.properties");
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
1

To understand that, you have to understand that String is an instance (object) of its superclass (parent class) Object.

class String's instance (object)'s value is a String literal (e.g. "I am a string.") :

class   |  instance (object) |  literal
------------------------------------------------
String  |  instance_name  =  |  "I am a string."

whereas class Object's instance (object)'s value is a Class literal — (e.g. Hashtable.class) which refers to class Hashtable's instance (object)

class      |  instance (object) |  literal
------------------------------------------------
Hashtable  |  instance_name     |  Hashtable.
AppTime
  • 37
  • 7
1

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:

Class<Bicycle> bicycleClass = Bicycle.class; // returns the object storing your Bicycle class
bicycleClass.getName();  // returns your class name
bicycleClass.getDeclaredMethods();  // returns your (declared) class methods
Emmanuel Osimosu
  • 5,625
  • 2
  • 38
  • 39
-1
package training;

import java.lang.reflect.Method;

public class Training {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Class<Training> myclass = Training.class;
        Method[] myclassarr = myclass.getDeclaredMethods();
        System.out.println(myclass);
        System.out.println(myclass.getName());
        for (int i = 0; i < myclassarr.length; i++) {
            System.out.println(myclassarr[i]);
        }
        System.out.println();
        Class<String> strobj = String.class;
        System.out.println(strobj);
        System.out.println(strobj.getName());
        Method[] strobjarr = strobj.getDeclaredMethods();
        for (int j = 0; j < strobjarr.length; j++) {
            System.out.println(strobjarr[j]);
        }
    }

    public void MethodA() {

    }

    public static void MethodB() {

    }
}

Output:

class training.Training
training.Training
public static void training.Training.main(java.lang.String[])
public void training.Training.MethodA()
public static void training.Training.MethodB()

class java.lang.String
java.lang.String
public boolean java.lang.String.equals(java.lang.Object)
public java.lang.String java.lang.String.toString()
public int java.lang.String.hashCode()
public int java.lang.String.compareTo(java.lang.String)
public int java.lang.String.compareTo(java.lang.Object)
public int java.lang.String.indexOf(java.lang.String,int)
public int java.lang.String.indexOf(java.lang.String)
public int java.lang.String.indexOf(int,int)
public int java.lang.String.indexOf(int)
static int java.lang.String.indexOf(char[],int,int,char[],int,int,int)
static int java.lang.String.indexOf(char[],int,int,java.lang.String,int)
public static java.lang.String java.lang.String.valueOf(int)
public static java.lang.String java.lang.String.valueOf(long)
public static java.lang.String java.lang.String.valueOf(float)
public static java.lang.String java.lang.String.valueOf(boolean)
public static java.lang.String java.lang.String.valueOf(char[])
public static java.lang.String java.lang.String.valueOf(char[],int,int)
public static java.lang.String java.lang.String.valueOf(java.lang.Object)
public static java.lang.String java.lang.String.valueOf(char)
public static java.lang.String java.lang.String.valueOf(double)
public char java.lang.String.charAt(int)
private static void java.lang.String.checkBounds(byte[],int,int)
public int java.lang.String.codePointAt(int)
public int java.lang.String.codePointBefore(int)
public int java.lang.String.codePointCount(int,int)
public int java.lang.String.compareToIgnoreCase(java.lang.String)
public java.lang.String java.lang.String.concat(java.lang.String)
public boolean java.lang.String.contains(java.lang.CharSequence)
public boolean java.lang.String.contentEquals(java.lang.CharSequence)
public boolean java.lang.String.contentEquals(java.lang.StringBuffer)
public static java.lang.String java.lang.String.copyValueOf(char[])
public static java.lang.String java.lang.String.copyValueOf(char[],int,int)
public boolean java.lang.String.endsWith(java.lang.String)
public boolean java.lang.String.equalsIgnoreCase(java.lang.String)
public static java.lang.String java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object[])
public static java.lang.String java.lang.String.format(java.lang.String,java.lang.Object[])
public void java.lang.String.getBytes(int,int,byte[],int)
public byte[] java.lang.String.getBytes(java.nio.charset.Charset)
public byte[] java.lang.String.getBytes(java.lang.String) throws java.io.UnsupportedEncodingException
public byte[] java.lang.String.getBytes()
public void java.lang.String.getChars(int,int,char[],int)
void java.lang.String.getChars(char[],int)
private int java.lang.String.indexOfSupplementary(int,int)
public native java.lang.String java.lang.String.intern()
public boolean java.lang.String.isEmpty()
public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.CharSequence[])
public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.Iterable)
public int java.lang.String.lastIndexOf(int)
public int java.lang.String.lastIndexOf(java.lang.String)
static int java.lang.String.lastIndexOf(char[],int,int,java.lang.String,int)
public int java.lang.String.lastIndexOf(java.lang.String,int)
public int java.lang.String.lastIndexOf(int,int)
static int java.lang.String.lastIndexOf(char[],int,int,char[],int,int,int)
private int java.lang.String.lastIndexOfSupplementary(int,int)
public int java.lang.String.length()
public boolean java.lang.String.matches(java.lang.String)
private boolean java.lang.String.nonSyncContentEquals(java.lang.AbstractStringBuilder)
public int java.lang.String.offsetByCodePoints(int,int)
public boolean java.lang.String.regionMatches(int,java.lang.String,int,int)
public boolean java.lang.String.regionMatches(boolean,int,java.lang.String,int,int)
public java.lang.String java.lang.String.replace(char,char)
public java.lang.String java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence)
public java.lang.String java.lang.String.replaceAll(java.lang.String,java.lang.String)
public java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String)
public java.lang.String[] java.lang.String.split(java.lang.String)
public java.lang.String[] java.lang.String.split(java.lang.String,int)
public boolean java.lang.String.startsWith(java.lang.String,int)
public boolean java.lang.String.startsWith(java.lang.String)
public java.lang.CharSequence java.lang.String.subSequence(int,int)
public java.lang.String java.lang.String.substring(int)
public java.lang.String java.lang.String.substring(int,int)
public char[] java.lang.String.toCharArray()
public java.lang.String java.lang.String.toLowerCase(java.util.Locale)
public java.lang.String java.lang.String.toLowerCase()
public java.lang.String java.lang.String.toUpperCase()
public java.lang.String java.lang.String.toUpperCase(java.util.Locale)
public java.lang.String java.lang.String.trim()
Nisrin Dhoondia
  • 145
  • 1
  • 10
  • I have just answered what the person has asked in the question. "To what type of variable can this literal be assigned to? Please give a small example if possible." – Nisrin Dhoondia Apr 04 '19 at 10:39
  • My mistake for just posting the code. Please find below the link to get more details about - class literal in Java. https://www.linkedin.com/pulse/details-class-literal-java-nisrin-dhoondia – Nisrin Dhoondia Apr 05 '19 at 05:23