Java - newInstance() method

The newInstance() method of Class class and Constructor class is used to create a new instance of the 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 of it as Object class. You will learn about generics later.

newInstance() Method Example-1

Let's see the simple example to use newInstance() method.

FileName: Test.java

class Simple{  
 void message(){System.out.println("Hello Java");}  
}  

class Test{  
 public static void main(String args[]){  
  try{  
  Class c=Class.forName("Simple");  
  Simple s=(Simple)c.newInstance();  
  s.message();  
  
  }catch(Exception e){System.out.println(e);}  
  
 }  
}  

Output:

Hello java

newInstance() method Example-2

We have learned in the introductory part of this topic that the newInstance() method of the Class class can only invoke the parameterless constructor. Let's understand the same with the help of an example.

FileName: ReflectionExample1.java


// important import statements  
import static java.lang.System.out;  
import java.lang.reflect.*;  
import javax.swing.*;  
  
public class ReflectionExample1  
{  
// Allowing Java Virtual Machine to handle the ClassNotFoundException  
// main method  
public static void main(String argvs[]) throws ClassNotFoundException  
{  
  
Object ob = null;  
Class classDefinition = Class.forName("javax.swing.JLabel");  
ob = classDefinition.newInstance();  
      
// instance variable for holding the instance of the class  
JLabel l1;  
  
// checking whether the created object ob is  
// the instance of JLabel or not.  
// If yes, do the typecasting; otherwise, terminate the method  
if(ob instanceof JLabel)  
{  
l1 = (JLabel)ob;  
}  
else  
{  
return;  
}  
  
// reaching here means the typecasting has been done  
// now we can invoke the getText() method  
out.println(l1.getText());  
  
}  
}  

Output:

/ReflectionExample1.java:15: error: unreported exception InstantiationException; must be caught or declared to be thrown

ob = classDefinition.newInstance();

Note: /ReflectionExample1.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

1 error

Explanation: The newInstance() method of the Class class only invokes the zero-argument constructor. However, we need to invoke the non-zero argument constructor for that, we need to use the newInstance() method of the class Constructor.

The following program shows how one can use the newInstance() method of the class Constructor to avoid the exception that has come in the above example.

FileName: ReflectionExample2.java


// important import statements  
import static java.lang.System.out;  
import java.lang.reflect.*;  
import javax.swing.*;  
  
public class ReflectionExample2  
{  
// main method  
public static void main(String argvs[])   
{  
try   
{  
Class[] t = { String.class };  
Class classDef = Class.forName("javax.swing.JLabel");   
  
// getting the constructor  
Constructor cons = classDef.getConstructor(t);  
  
// setting the label  
Object[] objct = { "My JLabel in Reflection."};  
  
// getting the instance by invoking the correct constructor this time  
Object ob = cons.newInstance(objct);  
  
  
// instance variable for holding the instance of the class  
JLabel l1;  
  
// checking whether the created object ob is  
// the instance of JLabel or not.  
// If yes, do the typecasting; otherwise, exit from the method  
if(ob instanceof JLabel)  
{  
l1 = (JLabel)ob;  
}  
else  
{  
// exiting from the method using the return statement  
return;  
}  
  
// if the control reaches here, then it means the typecasting has been done  
// now we can print the label of the JLabel instance  
out.println(l1.getText());  
}  
// relevant catch block for handling the raised exceptions.  
catch (InstantiationException ie)   
{  
out.println(ie);  
}   
catch (IllegalAccessException ie)   
{  
System.out.println(ie);  
}    
      
catch (InvocationTargetException ie)   
{  
out.println(ie);  
}  
catch (ClassNotFoundException e)   
{  
out.println(e);  
}  
      
catch (NoSuchMethodException e)   
{  
out.println(e);  
}  
}  
}  

Output:

My JLabel in Reflection.