Friday, October 1, 2010

What is the use of class “java.lang.Class” ? why do we need Class.forName() and Class.newInstance() method if we can create object using new()?

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");
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.


Jegan said...

Nice article... Thanks for sharing the information. Good to refresh known stuffs.

Anonymous said...

Used by Classloaders too when loading classes.

Javin @ FIX Protocol Tutorial said...

@Jegan and Anonymous , good to know that you find this java class blog post useful, thanks for your comments.

Javin @ SQL Select command Examples said...

Thanks for your Comment Michee. good to know that you like my Java Blog. your suggestions will always be welcome.

N.satish babu said...

hi javin, is class.forName() and class.newInstance() are factory design patterns right?

periasamy G said...

mr javin i m big reader of ur blog, as usual it is good article.
i hv one doubt can v use getclass() instead of instance of operator to check 2 objs r blong to same class?

Beenish Zaidi said...

Javin, does it mean that only one instance of java.lang.Class is made and it shared among all instances of the class. Is it singleton in nature?

Mayank said...

Nice articles you have :)

Post a Comment