FAQ

Java

JSP

Servlet


Advertisement



How to use class literals?

Java language supports dynamic loading of classes (e.g., What does Class.forname("x") method do?). For example, you can use:

   Class c = Class.forName("java.lang.String");

to retrieve a Class object representing the class java.lang.String, which is a special class used to represent classes. There is one Class object for each loaded class known to the Java runtime system.

The class literal is another way to produce the reference to the Class object. For example:

public class literal {
public static void main(String args[])
{
Class c = java.lang.String.class;
Class c2 = double.class;
Class c3 = Double.TYPE;

System.out.println(c);
System.out.println(c2);
System.out.println(c3);
}
}

The class must be known at compile time otherwise a compile error is generated. The output of this program is:

   class java.lang.String
double
double

c in the program represents the loaded class java.lang.String, while c2 and c3 represent the primitive data type double. Double is a wrapper class for double, and TYPE a special member within the class that represents its underlying primitive type.

According to specification, Class literals work with regular classes as well as interfaces, arrays, and primitive types. In addition, there is a standard field called TYPE that exists for each of the primitive wrapper classes. The TYPE field produces a reference to the Class object for the associated primitive type (see Inner Classes Specification), such that:

 
boolean.class == Boolean.TYPE
char.class == Character.TYPE
byte.class == Byte.TYPE
short.class == Short.TYPE
int.class == Integer.TYPE
long.class == Long.TYPE
float.class == Float.TYPE
double.class == Double.TYPE
void.class == Void.TYPE

You cannot use a variable with .class. For example:

class Program {
public static void main(String[] args) {
int i = 5;
String s = "Hello";

System.out.println(i.class); // compile error
System.out.println(s.class); // compile error
}
}

References

15.8.2 Class Literals
Inner Classes Specification


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |