The newInstance() method of Class class is used to create a new instance of the class dynamically. We all know Class.forName() is used in loading the class dynamically and we will be using newInstance() method on top of it to create object dynamically. The newInstance() method of Class class can invoke only no-arg constructor of the class.
Syntax :
public T newInstance() throws InstantiationException, IllegalAccessException
Creates a new instance of the class represented by the Class object.
Example of newInstance() method
Lets now take a look into the below example for a better understanding.
public class Test { public Test() { System.out.println("Inside Test class constructor"); } public void disp() { System.out.println("Disp() method called"); } } public class Logic { public static void main(String args[]) { try { String someClassName = "com.javainterviewpoint.Test"; Class clasz = Class.forName(someClassName); Test t = (Test)clasz.newInstance(); t.disp(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
Class.forName produces the object of type Class which encapsulates our “Test” class. The class Class has a method newInstance() which will create object for our Test class.
Output :
Inside Test class constructor Disp() method called
Leave a Reply