Friday, July 27, 2012

what is the use of Class.forName() instantiation?

java.lang.Class is one of the most important class in java but oftenly overlooked by java developers.

Every 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. This method is inherited from java.lang.Object

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 clas 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.

this 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.

No comments:

Post a Comment