Creating Java Object without new Keyword using Reflection

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:

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 Reply

Your email address will not be published. Required fields are marked *