There are 3 ways to get the object of a Class class. They are as
follows:
1 forName() method of Class class
Used to load the class dynamically.
Returns the instance of Class class.
It should be used if you know the fully qualified name of class.This cannot be
used for primitive types.
Example of forName() method
class Demo{}
class Test{
public static void main(String args[]){
Class c=Class.forName("Demo");
System.out.println(c.getName());
}
}
2 getClass() method of Object class
It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.
Example of getClass() method
class Demo{}
class Test{
void printName(Object obj){
Class c=obj.getClass();
System.out.println(c.getName());
}
public static void main(String args[]){
Demo d=new Demo();
Test t=new Test();
t.printName(d);
}
}
3 The .class syntax
If a type is available but there is no instance then it is possible to
obtain a Class by appending ".class" to the name of the type.It can be used for
primitive data type also.
Example of .class syntax
class Test{
public static void main(String args[]){
Class c = boolean.class;
System.out.println(c.getName());
Class c1 = Test.class;
System.out.println(c1.getName());
}
}
Read More →