问题
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?
回答1:
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 }
回答2:
An array initializer of the following form does not use new
explicitly.
int ia[][] = { {1, 2}, null };
This creates an object ... by autoboxing:
Integer big = 9999;
Finally, the following result in the creation of objects somewhere in the program's lifecycle :-)
Class c = ThisClass.class;
String s = "a literal";
enum SomeEnum { WON, CHEW, TREE }
(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 3 new array
bytecodes. That probably includes all of my examples.
Interestingly, Object.clone()
and ObjectInputStream.readObject()
both use "magic" mechanisms for creating instances that don't involve the above bytecodes, and don't call constructors in the normal way.
回答3:
your could use the jdbc's way
Class.forName("YOURCLASSNAME").newInstance()
回答4:
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.
- implement "Cloneable" interface to each class which you want to clone. If a class does not implement "Cloneable" interface, clone method will throw "CloneableNotSupportedException". This interface does not contain any methods. It is just a marker interface.
Example for String class
String sample = new String();
Now we are not going to use new operator and we will create a new object
String sampleClone = sample.clone();
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
回答5:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectCreateDifferentWays {
public static void main(String[] args) throws Exception {
///1st Way with newInstance()
Class cls = Class.forName("Student");
Student ob1 = (Student) cls.newInstance();
ob1.display();
///2nd Way with new Operator
Student ob2 = new Student();
ob2.display();
//3rd Way with clone
Student ob3 = (Student) ob2.clone();
ob3.display();
//4th Way with Deserialization
FileOutputStream out = new FileOutputStream("file.txt");
ObjectOutputStream obOut = new ObjectOutputStream(out);
obOut.writeObject(ob2);
obOut.flush();
FileInputStream fIn = new FileInputStream("file.txt");
ObjectInputStream obIn = new ObjectInputStream(fIn);
Student ob4 = (Student) obIn.readObject();
ob4.display();
}
}
class Student implements Cloneable, Serializable {
public void display() throws Exception {
System.out.println("Display ");
}@
Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
There are some ways to create object in Java 1) newInstance() method 2) new operator 3) clone() method 4) Deserialization
回答6:
You can deserialize an object without invoking new.
Ok, you have to call new
on the FileInputStream
and the ObjectInputStream
, but I assume that is fair use.
FileInputStream fis = new FileInputStream("myClassInstance.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
MyClass myObject = (MyClass)ois.readObject();
回答7:
AFAIK, Class.newInstance() and Constructor.newInstance() don't use the new
keyword internally.
Other ways to create an instance without the new keyword:
- Object.clone()
- Serialization
回答8:
There are only three standard ways to instantiate a class without the use of the new operator, and they are as follows:
- newInstance()
- clone()
- De-serialization
来源:https://stackoverflow.com/questions/16607261/instantiate-objects-without-using-new-operator