1. 浅克隆

@Data
class User implements Cloneable {

    private String username;

    private List<String> hobbyList;

    /**
     * 浅克隆,复制基本数据类型的数据,复制引用数据类型的地址
     */
    @Override
    protected Object clone() {
        User user = null;
        try {
            user = (User) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println("拷贝失败");
        }
        return user;
    }
}

2. 深克隆

@Data
class User implements Cloneable, Serializable {

    private static final long serialVersionUID = 6363235412193030603L;

    private String username;

    private List<String> hobbyList;

    /**
     * 浅克隆,复制基本数据类型的数据,生成新的引用数据对象
     */
    @Override
    protected Object clone() {
        ObjectInputStream objectInputStream = null;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            // 将对象写入流中
            objectOutputStream.writeObject(this);
            objectInputStream = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            // 将对象从流中取出
            User user = (User) objectInputStream.readObject();
            objectInputStream.close();
            return user;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

3. 测试

public class Test {

    public static void main(String[] args) {
        User user = new User();
        user.setHobbyList(Lists.newArrayList("吃饭", "睡觉"));
        user.setUsername("chenkaixin12121");

        User user2 = (User) user.clone();
        user2.setUsername("chenkaixin");
        user2.getHobbyList().add("打豆豆");

        System.out.println(user);
        System.out.println(user2);
    }
}

Q.E.D.


盛年不重来,一日难再晨。