Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate objects without using new operator

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?

like image 529
Arun Avatar asked May 17 '13 10:05

Arun


People also ask

Will you be able to instantiate the object without new operator?

In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object.

Why do we use the new operator when instantiating an object?

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Can you instantiate an object without a constructor?

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

Can we create object without using new keyword in C#?

This is the easiest way to instantiate an object. It's as easy as creating a variable or calling a static method. There are no restrictions on where to create an object with a new keyword.


1 Answers

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 }
like image 130
sanbhat Avatar answered Sep 19 '22 20:09

sanbhat