Class class can list everything about a class at runtime.
You can get the reference to the Class object of a class in one of the followings ways:
A class literal is the class name followed by a dot and the word "class."
For example, String class literal is String.class and you can write
Class<String> c = String.class;
You can get the class object for primitive data types and the keyword void using class literals as boolean.class, byte.class, char.class, short.class, int.class, long.class, float.class, double.class, and void.class.
Each wrapper class for these primitive data types has a static field named TYPE, which has the reference to the class object of the primitive data type it represents.
int.class and Integer.TYPE refer to the same class object and the expression int.class == Integer.TYPE evaluates to true.
The following table shows the class literals for all primitive data types and the void keyword.
Data Type | Primitive Class Literal | Wrapper Class Static Field |
---|---|---|
boolean | boolean.class | Boolean.TYPE |
byte | byte.class | Byte.TYPE |
char | char.class | Character.TYPE |
short | short.class | Short.TYPE |
int | int.class | Integer.TYPE |
long | long.class | Long.TYPE |
float | float.class | Float.TYPE |
double | double.class | Double.TYPE |
void | void.class | Void.TYPE |
Object class getClass() method returns the reference to the Class object.
You can get the reference to the Class object of the Test class as follows:
Test testRef = new Test(); Class<? extends Test> testClass = testRef.getClass();
Class class forName() static method returns a reference to a Class object.
It is an overloaded method The declarations of the two overloaded versions of this method are
Class<?> forName(String className)
Class<?> forName(String name, boolean initialize, ClassLoader loader)
To load a class named pkg1.Test, you would write
Class testClass = Class.forName("pkg1.Test");
class Test { static {/*www . j a va 2s . com*/ // This will execute when this class is loaded and initialized System.out.println("Loading class Bulb..."); } } public class Main { public static void main(String[] args) { createObject(); forName(); forNameVersion2(); classLiteral(); } public static void classLiteral() { Class<Test> c = Test.class; } public static void forNameVersion2() { try { String className = "Test"; boolean initialize = false; ClassLoader cLoader = Main.class.getClassLoader(); Class c = Class.forName(className, initialize, cLoader); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } } public static void forName() { try { String className = "com.book2s.reflection.Bulb"; Class c = Class.forName(className); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } } public static void createObject() { new Test(); } }