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
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?