The newInstance() method of Class class and Constructor class is used to create a new instance of the given class by calling the constructor of given class .

The newInstance() method of Class class can invoke zero-argument constructor whereas newInstance() method of Constructor class can invoke any number of arguments. So Constructor class is preferred over Class class.

  • Syntax of newInstance() method of Class class

    public T newInstance()throws InstantiationException, IllegalAccessException
    Here T is the generic version. You can think it like Object class. You will learn about generics later.

    Example)
    drag_handle
     class MyClass {
    	public void test() {
    		System.out.println("This is test method of MyClass");
    	}
    }
    
    class Test {
    	public static void main(String[] args) throws ClassNotFoundException,
    			InstantiationException, IllegalAccessException {
    		Class c = Class.forName("MyClass");
    		MyClass myclass = (MyClass) c.newInstance();
    		myclass.test();
    	}
    }
    Output:
    This is test method of MyClass
    

What next?

The next topic is reflect package in java

Share this page