2010-10-18 69 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();