Creating Java Object without new Keyword using Reflection


Object without new Keyword: We have seen four styles of creating a Java object without using new keyword. Now let us see with Reflection API Constructor class.
Example on Object without new Keyword:
import java.lang.reflect.*;
public class Demo
{
  int x = 10;
  public Demo() {  }      // default constructor. Even without it also program words as default is created implicitly
  public static void main(String args[]) throws Exception
  {     
    Class cl = Class.forName("Demo"); 
    Constructor con[] = cl.getDeclaredConstructors();
    Demo d1 = (Demo) con[0].newInstance();
    System.out.println(d1.x);		// prints 10
  }
}

Class cl = Class.forName(“Demo”);
Constructor con[] = cl.getDeclaredConstructors();

forName() method of class Class loads the class Demo into the RAM and returns a Class object. The Class object cl refers Demo.class. getDeclaredConstructors() method returns the list of all constructors in Demo class as an array of java.lang.reflect.Constructor class. The first element of con[] array contains the default constructor.

Demo d1 = (Demo) con[0].newInstance();

con[0] refers the default constructor using which Demo object d1 is created. Now d1 object is created without using new keyword.

Would you like to know all the 5 styles of creating Java object without using new keyword?

Leave a Comment

Your email address will not be published.