Instantiate objects without using new operator

Arun picture Arun · May 17, 2013 · Viewed 30.7k times · Source

In one of the java interview, the following question is asked:

In java is there a way to instantiate an object without using new operator? I replied to him that there is no other way of instantiation. But he asked me how an object in java is instantiated with the configurations in an xml file in java(in spring framework). I said, internally the spring uses reflection utils to create an object with a new operator. But the interviewer was not convinced with my answer.

I saw this link to be useful but there is a new operator indirectly involved in one or the other internal methods.

Is there really a way to instantiate objects in java without using new operator?

Answer

sanbhat picture sanbhat · May 17, 2013

You can do it using the Java Reflection API. That's how the Spring framework's DI works (instantiating object from xml).

Class<YourClass> c = YourClass.class;
YourClass instance = c.newInstance();

Also, Considering enum to be a special class, the instances of the enum are created without using new Operator.

public enum YourEnum { X, Y }