Java中创建对象的几种方式

Java中创建对象的几种方式:

  1. new
  2. 反序列化
  3. clone

克隆举例:

public class Teacher implements Cloneable{ // 可克隆的

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 必须调用Object父类的克隆方法
        return super.clone();
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Teacher t = new Teacher();
        t.setId(1);
        t.setName("满老师");

        Teacher t2 = (Teacher)t.clone();
        System.out.println(t2.getId());
        System.out.println(t2.getName());

        System.out.println(t2 == t);
    }
}

克隆对应的设计模式:原型(prototype)模式 ,不走构造方法,根据一个已有对象创建新的对象。

tips:

  1. 使用Cloneable接口和clone()克隆的对象为浅拷贝,如果属性为引用类型,克隆的仅仅是地址,并没有为这个属性创建新的对象。
  2. 利用序列化和反序列化生成新的对象为深拷贝 ,会为属性创建新的对象

例:

public class Teacher2 implements Serializable{

    private int id;
    private String name;
    private Date birthday;

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Teacher2 clone() {
        try {
            // 序列化
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos);
            os.writeObject(this); // 写入当前对象
            byte[] bytes = bos.toByteArray(); // 字节结果

            // 反序列化
            ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(bytes));
            Teacher2 t = (Teacher2)is.readObject();
            return t;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Teacher2 t = new Teacher2();
        t.setId(1);
        t.setName("满老师");
        t.setBirthday(new Date());

        Teacher2 t2 = t.clone();

        System.out.println(t == t2);
        System.out.println(t.getBirthday() == t2.getBirthday());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值