Site icon Narayana Tutorial

Difference between Class.forName() and newInstance() in java

Difference between Class.forName() and newInstance() in java

 

Class.forName() returns the Class-Type for the given name. Means that it will return reference to a class and load the available all static blocks not instance methods.

if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:

Class.forName("Somthing");

 

newInstance() does return an instance of this class. It will return object of that class so we can call the instance methods through object.

if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:

Class.forName("Somthing").newInstance();
Class.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass();
 

 

package narayanatutorial;


public class ClassForNameTest2 {

    public void getData() {
        System.out.println("getData method executing......");
    }
}

------------------------------------------------------------------------------------------

package narayanatutorial;

import java.lang.reflect.Method;

public class ClassForNameTest {

    public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class loadclass = Class.forName("narayanatutorial.ClassForNameTest2");
        System.out.println("number of methods:" + loadclass.getMethods().length);
        Method[] method = loadclass.getMethods();
        for (Method m : method) {
            System.out.println("Method Names:" + m.getName());
        }
        ClassForNameTest2 obj = (ClassForNameTest2) loadclass.newInstance();
        obj.getData();
    }
}




output

number of methods:10
Method Names:getData
Method Names:wait
Method Names:wait
Method Names:wait
Method Names:equals
Method Names:toString
Method Names:hashCode
Method Names:getClass
Method Names:notify
Method Names:notifyAll
getData method executing......


 

I hope you understood the difference between Class.forName() and newInstance() . Please reply in comments.