Java-clone()

0. 相关:浅拷贝与深拷贝

1. java.lang.Object类内的方法

  protected Object clone() throws CloneNotSupportedException

2. 作用:创建并返回此对象的副本。

3. 异常:CloneNotSupportedException

  如果对象的类不支持Cloneable接口,子类重写clone方法也抛出该异常表示实例无法克隆。

4. 实现对一个实体类的克隆,可以使用Object类的clone()方法,首先要使实体类实现Cloneable接口,并重写clone()方法,返回父类的clone()即可。

实例如下:

package com.basis.entity;

public class Person implements Cloneable {

    private String adress;
    private Info info;

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    public Info getInfo() {
        return info;
    }

    public void setInfo(Info info) {
        this.info = info;
    }

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

    public Object clone() throws CloneNotSupportedException{
        return super.clone();
    }
}
package com.basis.entity;

public class Info {

    private String IDCard;
    private String name;

    public String getIDCard() {
        return IDCard;
    }

    public void setIDCard(String IDCard) {
        this.IDCard = IDCard;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Info{" +
                "IDCard='" + IDCard + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
package com.company;

import com.basis.entity.Info;
import com.basis.entity.Person;

public class Main {

    public static void main(String[] args) {

        Info info = new Info();
        info.setName("张三");
        info.setIDCard("111111");

        Person person1 = new Person();
        person1.setAdress("北京");
        person1.setInfo(info);

        System.out.println(person1.toString());

        Person person2 = null;
        try {
            person2 = (Person)person1.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        System.out.println(person2.toString());

    }
}

结果:

Person{adress='北京', info=Info{IDCard='111111', name='张三'}}
Person{adress='北京', info=Info{IDCard='111111', name='张三'}}

 

你可能感兴趣的:(Java-clone())