Java建立物件的五個方法

1. 直接new一個物件

MyObject object = new MyObject();

2. 取得class後newInstance()

MyObject object = MyObject.class.newInstance();
MyObject object = (MyObject) Class.forName("package.MyObject").newInstance();
MyObject object = (MyObject) Class.forName("package.MyObject").getDeclaredConstructor().newInstance();

3. 取得Constructor後newInstance()

Constructor<MyObject> constructor = MyObject.class.getConstructor();
MyObject object = constructor.newInstance();

4. 使用Clone

MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();

5. 使用input stream反序列化

ObjectInputStream inStream = new ObjectInputStream(anInputStream);
MyObject object = (MyObject) inStream.readObject();