java.lang.Class is one of the most important class in java but mostly overlooked by Java developers. It is very useful in the sense that it provides several utility methods e.g. getClass(), forName() which is used to find and load a class, you might have used to load Oracle or MySQL drivers. It also provides methods like Class.newInstance() which is the backbone of reflection and allow you to create instance of a class without using new() operator. Class has no public constructor and it's instance is created by JVM when a class is loaded. Object of class Class is also used to represent classes, enum, interfaces and annotation in a running Java application. The primitive types e.g. byte, short, char, int, float, double and boolean are also represent by Class instances. You can get the corresponding Class instance by using class literals e.g. int.class, float.class or boolean.class. It is also used to represent instance of array in Java. Every array with same type and same dimension share same instance of class Class. Another use of java.lang.Class is while implementing equals() method to check whether two objects are of same type or not.
java.lang.Class class in Java

Suppose you create two instances of class called Person e.g.
Person A = new Person();
Person B = new Person();
if(A.getClass() == B.getClass()){
System.out.println("A and B are instances of same class");
}else{
System.out.println("A and B are instances of different class");
}
In this case it will print "A and B are instances of same class" because they are both instance of class Person.
We need forName() and newInstance() because many times it happens that we don’t know the name of the class to instantiate while writing code , we may get it from config files, database,network or from any upstream Java or C++ application.
This is what we called reflective way of creating object which is one of the most powerful feature of Java and which makes way for many frameworks e.g. Spring ,Struts which uses Java reflection.
Tidak ada komentar:
Posting Komentar