2010-10-18 66 views
-3

可能重复:
is there any other way of creating an object without using “new” keyword in java创建对象的

多少种方法都没有在Java中创建一个对象?

+2

为什么? ................... – 2010-10-18 11:00:41

+3

请参阅http://stackoverflow.com/questions/2103089/is-there-any-other-way-of-creating-an-object -without-using-new-keyword-in-java/2103146#2103146 – stacker 2010-10-18 11:01:30

+0

你想做什么? – smola 2010-10-18 11:03:51

回答

1
//Using reflection 
Class classObj Class.forName("Foo"); 
Foo obj1 (Foo)classObj.newInstance(); 

//new operator 
Foo obj2 new Foo(); 

//cloning 
Foo obj3 (TestObjectCreation)obj1.clone(); 

//deserialization 
ByteArrayOutputStream baos new ByteArrayOutputStream(); 
ObjectOutputStream oos new ObjectOutputStream(baos); 
oos.writeObject(obj1); 
ByteArrayInputStream bais new ByteArrayInputStream(baos.toByteArray()); 
ObjectInputStream ois new ObjectInputStream(bais); 
Foo obj4 (Foo)ois.readObject(); 
obj4.method1();