Java-deepcopy

Reference:  https://www.baeldung.com/java-immutable-object
From: https://github.com/eugenp/tutorials/tree/master/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/deepcopy
package com.baeldung.deepcopy;
import java.io.Serializable;
public class Address implements Serializable, Cloneable {
    @Override
    public Object clone() {
        try {
            return (Address) super.clone();
        } catch (CloneNotSupportedException e) {
            return new Address(this.street, this.getCity(), this.getCountry());
        }
    }
    private static final long serialVersionUID = 1740913841244949416L;
    private String street;
    private String city;
    private String country;
    public Address(Address that) {
        this(that.getStreet(), that.getCity(), that.getCountry());
    }
    public Address(String street, String city, String country) {
        this.street = street;
        this.city = city;
        this.country = country;
    }
    public Address() {
    }
    public String getStreet() {
        return street;
    }
    public String getCity() {
        return city;
    }
    public String getCountry() {
        return country;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public void setCountry(String country) {
        this.country = country;
    }
}
package com.baeldung.deepcopy;
import java.io.Serializable;
public class User implements Serializable, Cloneable {
    private static final long serialVersionUID = -3427002229954777557L;
    private String firstName;
    private String lastName;
    private Address address;

    public User(String firstName, String lastName, Address address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    }
    public User(User that) {
        this(that.getFirstName(), that.getLastName(), new Address(that.getAddress()));
    }
    public User() {
    }
    @Override
    public Object clone() {
        User user;
        try {
            user = (User) super.clone();
        } catch (CloneNotSupportedException e) {
            user = new User(this.getFirstName(), this.getLastName(), this.getAddress());
        }
        user.address = (Address) this.address.clone();
        return user;
    }
    public String getFirstName() {
        return firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public Address getAddress() {
        return address;
    }
}

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE