«Back to Home

Core Java

Topics

newInstance() Method In Java

newInstance() method
 
In Java, newInstance() method of Class “class” and Constructor class creates a new instance of the class. The newInstance() method of Class “class” can call zero-argument constructor but newInstance() method of Constructor class can call any number of arguments. Thus, Constructor class is preferred over Class “class”.
 
Syntax

public T newInstance()throws InstantiationException,IllegalAccessException
 
In this, T is the generic version. We can think it like Object class.
 
Let's see an example of newInstance() method.
 
Code
  1. class Reflection {  
  2.     void message() {  
  3.         System.out.println("Java Reflection");  
  4.     }  
  5. }  
  6. public class Example {  
  7.     public static void main(String args[]) {  
  8.         try {  
  9.             Class c = Class.forName("Reflection");  
  10.             Reflection r = (Reflection) c.newInstance();  
  11.             r.message();  
  12.         } catch (Exception e) {  
  13.             System.out.println(e);  
  14.         }  
  15.     }  
  16. }  
75

Summary

Thus, we learnt that Java newInstance() method of Class “class” and Constructor class creates a new instance of the class and also learnt how we can use it in Java.