java copy of the object in several ways

method one

Implement the Cloneable interface override clone () method

Examples of objects

@Data
public class User implements Cloneable,Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private List list = new ArrayList<String>();


    @Override
    public User clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return (User)clone;
    }

}

Analysis: clone () method of copying, advantage of this method is to use a direct interface to the parent clone () method of direct copy of an object, while the basic data types can be copied, but references the data types can not be copied, the original object and copy target attribute is a reference to the same attribute, it is often said that to copy a shallow copy, the following test

@Test
    public void testNewInstance() throws IllegalAccessException, InstantiationException {
        User user = new User();
        user.setName("111");
        User clone = user.clone();
        List list = user.getList();
        //给原对象中的list进行赋值
        list.add("hello");
        //获取拷贝对象的list属性
        List cloneList = clone.getList();
        Object o = cloneList.get(0);
        System.out.println(clone.getName());//输出为111
        System.out.println(o.toString());//输出结果为hell0,说明引用的是同一个ArrayList对象
    }

Second way

Serialization copy object implements Serializable interface, and write serialVersionUID 

Analysis: the ability to complete copy of the object, including a reference type attribute, but need to write your own serialization process, the following test

 @Test
    public void testSerializable() throws Exception {
        User user = new User();
        user.setName("111");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(user);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        User cloneUser = (User) objectInputStream.readObject();
        List list = user.getList();
        list.add("hello");
        List cloneUserList = cloneUser.getList();
        System.out.println(cloneUserList.size());//输出为0,说明原对象list属性的改变对克隆对象的引用属性无影响,也就是不是引用的同一个对象,拷贝成功
        System.out.println(cloneUser.getName());//输出111,拷贝成功

    }

Note: Why write serialVersionUID, mainly for de-serialization, if not the only UID, once the original class structure has changed, you can not deserialize

Guess you like

Origin blog.csdn.net/ly853602/article/details/84679885
Recommended