对象的5种生成方式

1.

class Person implements CloneableSerializable{
    public String name;
    public Person() {   
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }
}
Person p1 = new Person();

2

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));
out.writeObject(p1);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Person emp5 = (Person) in.readObject();
in.close();

3

要重写构造方法

Person p3 = Person .class.newInstance();

4

要重写构造方法

Constructor<Person> constructor =  Person.class.getConstructor();
Person p4 = constructor.newInstance();

5

(必须继承cloneable接口并实现clone方法)

Person p5 = (Person) p1.clone(); 

猜你喜欢

转载自blog.csdn.net/qq_41706670/article/details/82595282
今日推荐