Rabu, 05 Februari 2014

What is the use of class “java.lang.Class” in Java?



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


What is java.lang.Class in JavaEvery time JVM creates an object, it also creates a java.lang.Class object that describes the type of the object. All instances of the same class share the same Class object and you can obtain the Class object by calling the getClass() method of the object. By the way this method is inherited from java.lang.Object class.



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.























Source:http://javarevisited.blogspot.com/2010/10/what-is-use-of-class-javalangclass-why.html

Tidak ada komentar:

Posting Komentar