1.new创建新对象
2.通过反射机制
3.采用clone机制
4.通过序列化机制
前两者都需要显式地调用构造方法。对于clone机制,需要注意浅拷贝和深拷贝的区别,对于序列化机制需要明确其实现原理,在java中序列化可以通过实现Externalizable或者Serializable来实现。
package org.example;
import java.io.*;
public class Test03 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, CloneNotSupportedException, IOException {
// 创建对象的四种方式
// 1.new 出来
Person person = new Person();
person.show();
// 2.反射方式
Class<?> clazz = Class.forName("org.example.Person");
Person person1 = (Person) clazz.newInstance();
person1.show();
// 3.使用克隆的clone()方法创建对象
Person person2 = person.clone();
person2.show();
// 4.使用序列化和反序列化创建对象:
// 序列化对象
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(person);
// 反序列化
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Person person3 = (Person) ois.readObject();
person3.show();
}
}