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?
AFAIK, Class.newInstance() and Constructor.newInstance() don't use the
new
keyword internally.Other ways to create an instance without the new keyword:
There are only three standard ways to instantiate a class without the use of the new operator, and they are as follows:
You can use
clone
method to create a copy of object without new operator.clone is used to make a copy of object. There are certain things which you should keep in mind while using clone method of Object.
Example for String class
Now we are not going to use new operator and we will create a new object
Other you can use Class.forName()
public static Class forName(String className) throws ClassNotFoundException
Returns the Class object associated with the class or interface with the given string name.
Example -- Class exampleClass = Class.forName(yourtClass);
Read official docs
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName%28java.lang.String%29
An array initializer of the following form does not use
new
explicitly.This creates an object ... by autoboxing:
Finally, the following result in the creation of objects somewhere in the program's lifecycle :-)
(And there are many, many ways to do it using library methods ... or native code)
Underneath the covers, any creation of a new object in pure Java involves either the
new
bytecode, or one of 3new array
bytecodes. That probably includes all of my examples.Interestingly,
Object.clone()
andObjectInputStream.readObject()
both use "magic" mechanisms for creating instances that don't involve the above bytecodes, and don't call constructors in the normal way.You can deserialize an object without invoking new.
Ok, you have to call
new
on theFileInputStream
and theObjectInputStream
, but I assume that is fair use.You can do it using the Java Reflection API. That's how the Spring framework's DI works (instantiating object from xml).
Also, Considering
enum
to be aspecial class
, the instances of the enum are created without usingnew
Operator.