Java创建对象的几种方式

public class Main {
    
    private static final String FILE_NAME = "aa.out";

    public static void main(String[] args) {
        try {

            Person p1 = new Person("Tom");
            System.out.println("使用new创建对象:" + p1);

            Person p2 = Person.class.newInstance();
            System.out.println("使用class.newInstance创建对象:" + p2);

            //Constructor<Person> p3c = Person.class.getDeclaredConstructor(String.class);
            Constructor<Person> p3c = Person.class.getConstructor(String.class);
            Person p3 = p3c.newInstance("Jerry");
            System.out.println("使用Constructor创建对象:" + p3);


            Person p4 = p3.clone();
            System.out.println("使用clone()创建对象:" + p4);


            // Java序列化是指把Java对象转换为字节序列的过程,而Java反序列化是指把字节序列恢复为Java对象的过程;
            // 序列化对象
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME));
            oos.writeObject(p4);

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME));
            // 5、使用反序列化创建对象
            Person p5 = (Person) ois.readObject();
            System.out.println("使用反序列化创建对象:" + p5);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
import java.io.Serializable;
public class Person implements Cloneable, Serializable {
    String name;

    public Person() {
        this.name = "no name";
    }

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }

    @Override
    public Person clone() throws CloneNotSupportedException {
        return (Person) super.clone();
    }
}
WRITTEN BY: