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.
6 comments:
Nice article... Thanks for sharing the information. Good to refresh known stuffs.
Used by Classloaders too when loading classes.
@Jegan and Anonymous , good to know that you find this java class blog post useful, thanks for your comments.
cool blog!
Thanks for your Comment Michee. good to know that you like my Java Blog. your suggestions will always be welcome.
hi javin, is class.forName() and class.newInstance() are factory design patterns right?
Post a Comment