Monday, November 5, 2012

what is the difference between new operator and Class.forName


what is the difference between new operator and Class.forName


Maybe an example demonstrating how both methods are used will help you to understand things better. So, consider the following class:
package test;

public class Demo {

    public Demo() {
        System.out.println("Hi!");
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("test.Demo");
        Demo demo = (Demo) clazz.newInstance();
    }
}
As explained in its javadoc, calling Class.forName(String) returns the Class object associated with the class or interface with the given string name i.e. it returns test.Demo.class which is affected to the clazz variable of type Class.
Then, calling clazz.newInstance() creates a new instance of the class represented by this Classobject. The class is instantiated as if by a new expression with an empty argument list. In other words, this is here actually equivalent to a new Demo() and returns a new instance of Demo.

No comments:

Post a Comment