且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java对象的深度拷贝实现

更新时间:2022-03-26 04:24:51

1. 说明

Java对象复制可分为浅拷贝(shallow copy)和深度拷贝(deep copy)两种。浅拷贝指从源对象中将值复制出来,因此产生的拷贝对象与源对象并不是独立的。如源对象存在引用属性(reference),此时的拷贝对象和源对象的相同引用属性都指向同一个对象,修改引用属性对象的内容,对于拷贝对象和源对象都可见。深度拷贝指将源对象的对象图中所有对象都被拷贝一次,因此产生的拷贝对象与源对象是独立的。即引用属性的拷贝,也是将引用指向的对象拷贝一份。源对象的对象图中任何属性的改变,并不会影响拷贝对象的属性。

理解上面的含义后,我们下面将比较两种拷贝方式,并讨论4种深度拷贝的实现。

2. 准备

2.1 依赖

我们将使用Maven来管理项目依赖,需要引入Gson,JackSon,Apache Commons Lang。

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version>
</dependency>
<dependency>
  <groupId>commons-lang</groupId>
  <artifactId>commons-lang</artifactId>
  <version>2.6</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.6</version>
</dependency>

最新的GsonJackSonApache Commons Lang的版本可以在Maven Central仓库查看。

2.2 模型

我们需要引入2个对象类,来比较两种拷贝方式。

class Address {
    private String street;
    private String city;
    private String country;

    // standard constructors, getters and setters
}
class User {
    private String name;
    private Address address;
 
    // standard constructors, getters and setters
}

3. 浅拷贝

浅拷贝仅从源对象中复制属性的值,如果是引用属性,也只是复制引用的地址值。

import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;

import org.junit.Test;

@Test
public void shouldNotBeSame_WhenShallowCopy() {
    Address address = new Address("西湖区丰潭路380号", "杭州", "中国");
    User origin = new User("嗨皮的孩子", address);
    User shallowCopy = new User(origin.getName(), origin.getAddress());
    assertThat(shallowCopy, not(sameInstance(origin)));
}

在这种情况下origin != shallowCopy,也就是说前拷贝的对象与源对象是不同的。

import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

import org.junit.Test;

@Test
public void shouldCopyChange_whenModifyingOriginalObject() {
    Address address = new Address("西湖区丰潭路380号", "杭州", "中国");
    User origin = new User("嗨皮的孩子", address);
    User shallowCopy = new User(origin.getName(), origin.getAddress());
    address.setStreet("西湖区丰潭路381号");
    assertThat(shallowCopy.getAddress().getStreet(),equalTo(origin.getAddress().getStreet()));
}

在上面的测试中,我们改变源对象的地址属性中的street的值时,拷贝对象的地址属性中的street属性也跟着变化。

4. 深度拷贝

如果我们希望地址对象是不可变(immutable),我们要解决的方法是要在对象树中递归的拷贝每一个可变的对象。下面将讨论不同的方式来实现深度拷贝。

4.1 构造函数

基于复制构造函数实现深度拷贝。

public Address(Address that) {
    this(that.getStreet(), that.getCity(), that.getCountry());
}


public User(User that) {
    this(that.getName(), new Address(that.getAddress()));
}
import static org.junit.Assert.assertNotEquals;

import org.junit.Test;

@Test
public void shouldNotChange_WhenModifyingOriginalObject() {
    Address address = new Address("西湖区丰潭路380号", "杭州", "中国");
    User origin = new User("嗨皮的孩子", address);
    User shallowCopy = new User(origin);
    address.setStreet("西湖区丰潭路381号");
    assertNotEquals(shallowCopy.getAddress().getStreet(), origin.getAddress().getStreet());
}

基于构造函数实现的深度对象拷贝方法解决“拷贝对象”和“源对象”独立性问题。上述中,我们没有新建String对象,原因String是不可变对象类。

4.2 Cloneable 接口

基于Object#clone方法实现对象复制,但是Object#clone是protected方法,在覆写时,需要改成public修饰。我们需要在类的定义中实现Cloneable接口,标记对象是可以clone。

覆写Address类的clone方法

class Address implements Cloneable {
    private String street;
    private String city;
    private String country;
    // standard constructors, getters and setters

    ... ...
    
    @Override public Object clone(){
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            return new Address(this.street, this.getCity(), this.getCountry());
        }
    }
}

覆写User类的clone方法

class User implements Cloneable {
    private String name;
    private Address address;

    //standard constructors, getters and setters

    ... ...
    
    @Override public Object clone() {
        User user;
        try {
            user = (User) super.clone();
        } catch (CloneNotSupportedException e) {
            user = new User(this.getName(), this.getAddress());
        }
        user.address = (Address) this.address.clone();
        return user;
    }
}
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

import org.junit.Test;

@Test
public void shouldNotChange_WhenModifyingOriginalObjectUsingCloneCopy() {
    Address address = new Address("西湖区丰潭路380号", "杭州", "中国");
    User origin = new User("嗨皮的孩子", address);
    User shallowCopy = (User) origin.clone();
    address.setStreet("西湖区丰潭路381号");
    assertThat(shallowCopy.getAddress().getStreet(), not(equalTo(origin.getAddress().getStreet())));
}

super.clone方法实现的是浅拷贝,因此返回的为浅拷贝对象。我们需要对于可变对象的属性,重新设置新的值。

4.3 借助第三方库

前面提到2种深度拷贝方式很直观。但是当你不能添加额外的构造函数或者复写clone方法时,就需要借助第三方库实现深度拷贝。

核心的思想是“我们先系列化对象,然后再反系列化为新的对象”

4.3.1 Apache Commons Lang

Apache Commons Lang有SerializationUtils#clone方法,使用该方法可以深度复制出对象图中所有实现Serializable接口对象。此方法要求对象图中的类都实现Serializable接口,否则会抛出SerializationException。

class Address implements Serializable, Cloneable {
    private String street;
    private String city;
    private String country;
    // standard constructors, getters and setters

    ... ...
    
    @Override public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            return new Address(this.street, this.getCity(), this.getCountry());
        }
    }
}
class User implements Serializable, Cloneable {
    private String name;
    private Address address;

    //standard constructors, getters and setters

    ... ...
    
    @Override public Object clone() {
        User user;
        try {
            user = (User) super.clone();
        } catch (CloneNotSupportedException e) {
            user = new User(this.getName(), this.getAddress());
        }
        user.address = (Address) this.address.clone();
        return user;
    }
}
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

import org.apache.commons.lang.SerializationUtils;
import org.junit.Test;

@Test
public void shouldNotChange_WhenModifyingOriginalObjectUsingCommonsClone() {
    Address address = new Address("西湖区丰潭路380号", "杭州", "中国");
    User origin = new User("嗨皮的孩子", address);
    User shallowCopy = (User) SerializationUtils.clone(origin);
    address.setStreet("西湖区丰潭路381号");
    assertThat(shallowCopy.getAddress().getStreet(), not(equalTo(origin.getAddress().getStreet())));
}
4.3.2 使用Gson的JSON系列化

使用Json系列化方式,也可以的达到深度复制,Gson库可以用来将对象转为JSON,或从JSON转为对象。Gson不要求类实现Serializable接口。

class Address implements Serializable, Cloneable {
    private String street;
    private String city;
    private String country;

    public Address(String street, String city, String country) {
        this.street = street;
        this.city = city;
        this.country = country;
    }

    public Address(Address that) {
        this(that.getStreet(), that.getCity(), that.getCountry());
    }

    @Override public Object clone(){
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            return new Address(this.street, this.getCity(), this.getCountry());
        }
    }
    ... ...
    //getters and setters
}


class User implements Serializable, Cloneable {
    private String name;
    private Address address;

    public User(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    public User(User that) {
        this(that.getName(), new Address(that.getAddress()));
    }

    @Override public Object clone() {
        User user;
        try {
            user = (User) super.clone();
        } catch (CloneNotSupportedException e) {
            user = new User(this.getName(), this.getAddress());
        }
        user.address = (Address) this.address.clone();
        return user;
    }
    ... ...
    //getters and setters
}
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

import com.google.gson.Gson;
import org.junit.Test;

@Test
public void shouldNotChange_WhenModifyingOriginalObjectUsingGsonClone() {
    Address address = new Address("西湖区丰潭路380号", "杭州", "中国");
    User origin = new User("嗨皮的孩子", address);
    Gson gson = new Gson();
    User shallowCopy = gson.fromJson(gson.toJson(origin), User.class);
    address.setStreet("西湖区丰潭路381号");
    assertThat(shallowCopy.getAddress().getStreet(), not(equalTo(origin.getAddress().getStreet())));
}

4.3.3 使用Jackson的JSON系列化

Jackson是另一个JSON系列化库,实现上类似于Gson,但是我们需要给类提供默认构造函数。

class Address implements Serializable, Cloneable {
    private String street;
    private String city;
    private String country;

    public Address() {}

    public Address(String street, String city, String country) {
        this.street = street;
        this.city = city;
        this.country = country;
    }

    public Address(Address that) {
        this(that.getStreet(), that.getCity(), that.getCountry());
    }

    @Override public Object clone(){
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            return new Address(this.street, this.getCity(), this.getCountry());
        }
    }
    ... ...
    //getters and setters
}


class User implements Serializable, Cloneable {
    private String name;
    private Address address;

    public User() {}

    public User(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    public User(User that) {
        this(that.getName(), new Address(that.getAddress()));
    }

    @Override public Object clone() {
        User user;
        try {
            user = (User) super.clone();
        } catch (CloneNotSupportedException e) {
            user = new User(this.getName(), this.getAddress());
        }
        user.address = (Address) this.address.clone();
        return user;
    }
    ... ...
    //getters and setters
}
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.IOException;

@Test
public void shouldNotChange_WhenModifyingOriginalObjectUsingJacksonClone() throws IOException {
    Address address = new Address("西湖区丰潭路380号", "杭州", "中国");
    User origin = new User("嗨皮的孩子", address);
    ObjectMapper objectMapper = new ObjectMapper();
    User shallowCopy = objectMapper.readValue(objectMapper.writeValueAsString(origin), User.class);
    address.setStreet("西湖区丰潭路381号");
    assertThat(shallowCopy.getAddress().getStreet(), not(equalTo(origin.getAddress().getStreet())));
}

5. 总结

当我们需要深度复制对象时,该选择哪一种实现方式呢?依赖于我们需要复制的类,并且是否我们在对象图中拥有这些类。本文来自于java-deep-copy的翻译。

[1] : http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.google.code.gson%22%20AND%20a%3A%22gson%22 "Gson"
[2] : http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.fasterxml.jackson.core%22%20AND%20a%3A%22jackson-databind%22 "JackSon"
[3] : http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22commons-lang%22%20AND%20a%3A%22commons-lang%22 "Apache Commons Lang"
[4] : http://www.baeldung.com/java-deep-copy "java-deep-copy"