1.源码解析
protected native Object clone() throws CloneNotSupportedException;
创建并返回该对象的一个拷贝(Shallow-Copy),且这个“拷贝”的精确含义取决于该对象的类。如果该对象不支持Cloneable接口,则会抛出CloneNotSupportedException异常信息。
Object.clone()方法的通用约定如下:
对于任何对象x,表达式x.clone() != x返回true;
并且,表达式x.clone().getClass() == x.getClass()将会是true,但是这些都不是绝对的要求。
在通常情况下,表达式x.clone().equals(x)将会是true,但这也不是一个绝对的要求。
通用约定的解释:
按照惯例,应通过调用super.clone()方法获取返回的对象。如果一个类及其所有超类(Object除外)都遵守此约定,则x.clone().getClass()== x.getClass()就是这种情况。
按照惯例,super.clone()方法返回的对象应独立于源对象。为了实现这种独立性,可能有必要在返回之前修改super.clone()方法返回对象的一个或多个字段。通常,这意味着复制构成要克隆对象的内部“深度结构”的任何可变对象,并用对副本的引用替换对这些对象的引用。如果一个类仅包含基本字段或对不可变对象的引用,则通常情况下,无需修改super.clone()方法返回的对象中的任何字段。类Object的clone()方法执行特定的克隆操作。首先,如果此对象的类未实现接口Cloneable接口,则将引发CloneNotSupportedException。请注意,所有数组都被视为实现了接口Cloneable,数组类型为T []的clone方法的返回类型为T [],其中T为任何引用或原始类型。否则,此方法将创建此对象类的新实例,并使用该对象相应字段的内容完全初始化其所有字段,就像通过赋值一样;字段的内容本身不会被克隆。因此,此方法执行此对象的“浅拷贝”,而不是“深拷贝”操作。
2.通俗地讲一下浅拷贝和深拷贝
浅拷贝:创建并返回一个新对象,将当前对象的非static字段复制到该新对象。如果字段是基本类型,则复制该值;如果字段是引用类型,则复制引用。
如下图示例,类Employee拷贝一个新的Employee类对象,但共用一个Address类对象,但修改Address对象时,克隆的Employee类对象中的Address对象也会随之修改。
深拷贝:创建并返回一个新对象,将当前对象的非static字段复制到该新对象。无论该字段是值类型还是引用类型,都复制独立的一份。当你修改其中一个对象的任何内容时,都不会影响到另一个对象的内容。
3.如何实现深拷贝
(1)实现Cloneable接口,让每个引用类型的内部属性都重写clone方法。
public class Student implements Cloneable{
private int age;
private String name;
private Address address;
public Student(int age, String name, Address address) {
super();
this.age = age;
this.name = name;
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + ", address=" + address + "]";
}
@Override
protected Student clone() throws CloneNotSupportedException {
Student student = (Student)super.clone();
student.setAddress((Address) this.address.clone());
return student;
}
}
-------------------------------------------------------------------------------------------------------------------------------
public class Address implements Cloneable{
private String province;
private String city;
private String county;
public Address(String province, String city, String county) {
super();
this.province = province;
this.city = city;
this.county = county;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
@Override
public String toString() {
return "Address [province=" + province + ", city=" + city + ", county=" + county + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
return (Address)super.clone();
}
}
-------------------------------------------------------------------------------------------------------------------------------
public class StudentTest {
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("广东省", "深圳市", "福田区");
Student student = new Student(20,"Jack",address);
// 调用clone()方法进行深拷贝
Student studentCopy = student.clone();
// 修改拷贝对象的值以测试是否影响源对象的值
studentCopy.getAddress().setProvince("海南省");
studentCopy.getAddress().setCity("海口市");
studentCopy.getAddress().setCounty("龙华区");
System.out.println("The student is:" + student);
System.out.println("The studentCopy is:" + studentCopy);
}
}
输出结果为:
The student is:Student [age=20, name=Jack, address=Address [province=广东省, city=深圳市, county=福田区]]
The studentCopy is:Student [age=20, name=Jack, address=Address [province=海南省, city=海口市, county=龙华区]]
从输出结果来看,让每个引用类型内部属性都重写clone方法可以实现对象深拷贝。
(2)利用序列化和反序列化的方式进行深度克隆对象
import java.io.Serializable;
public class Student implements Serializable,Cloneable{
/**
*
*/
private static final long serialVersionUID = -4037743305421493766L;
private int age;
private String name;
private Address address;
public Student(int age, String name, Address address) {
super();
this.age = age;
this.name = name;
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + ", address=" + address + "]";
}
@Override
protected Student clone() throws CloneNotSupportedException {
Student student = (Student)super.clone();
student.setAddress((Address) this.address.clone());
return student;
}
}
-------------------------------------------------------------------------------------------------------------------------------
import java.io.Serializable;
public class Address implements Serializable,Cloneable{
/**
*
*/
private static final long serialVersionUID = -2704290616319012230L;
private String province;
private String city;
private String county;
public Address(String province, String city, String county) {
super();
this.province = province;
this.city = city;
this.county = county;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
@Override
public String toString() {
return "Address [province=" + province + ", city=" + city + ", county=" + county + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException {
return (Address)super.clone();
}
}
-------------------------------------------------------------------------------------------------------------------------------
import org.apache.commons.lang3.SerializationUtils;
/**
* @author Davince
*/
public class StudentTest {
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("广东省", "深圳市", "福田区");
Student student = new Student(20,"Jack",address);
// 调用clone()方法进行深拷贝
Student studentCopy = student.clone();
// 修改拷贝对象的值以测试是否影响源对象的值
studentCopy.getAddress().setProvince("海南省");
studentCopy.getAddress().setCity("海口市");
studentCopy.getAddress().setCounty("龙华区");
System.out.println("The student is:" + student);
System.out.println("The studentCopy is:" + studentCopy);
Address address2 = new Address("广东省", "广州市", "珠江新区");
Student student2 = new Student(20,"Rose",address2);
// 使用ApacheCommonsLang包序列化进行深拷贝
Student studentSerialization = SerializationUtils.clone(student2);
// 修改拷贝对象的值以测试是否影响源对象的值
studentSerialization.getAddress().setProvince("海南省");
studentSerialization.getAddress().setCity("三亚市");
studentSerialization.getAddress().setCounty("解放路");
System.out.println("The student2 is:" + student2);
System.out.println("The studentSerialization is:" + studentSerialization);
}
}
输出结果为:
The student is:Student [age=20, name=Jack, address=Address [province=广东省, city=深圳市, county=福田区]]
The studentCopy is:Student [age=20, name=Jack, address=Address [province=海南省, city=海口市, county=龙华区]]
The student2 is:Student [age=20, name=Rose, address=Address [province=广东省, city=广州市, county=珠江新区]]
The studentSerialization is:Student [age=20, name=Rose, address=Address [province=海南省, city=三亚市, county=解放路]]
从输出结果来看,让每个引用类型内部属性都重写clone方法和Java序列化反序列化的方法都可以实现对象深拷贝。
SerializationUtils工具类源码解析:封装了Java原生的序列化与反序列化,性能一般,可作为学习参考使用。
package org.apache.commons.lang3;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Assists with the serialization process and performs additional functionality based
* on serialization.</p>
*
* <ul>
* <li>Deep clone using serialization
* <li>Serialize managing finally and IOException
* <li>Deserialize managing finally and IOException
* </ul>
*
* <p>This class throws exceptions for invalid {@code null} inputs.
* Each method documents its behaviour in more detail.</p>
*
* <p>#ThreadSafe#</p>
* @since 1.0
*/
public class SerializationUtils {
/**
* <p>SerializationUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
* @since 2.0
*/
public SerializationUtils() {
super();
}
// Clone
//-----------------------------------------------------------------------
/**
* <p>Deep clone an {@code Object} using serialization.</p>
*
* <p>This is many times slower than writing clone methods by hand
* on all objects in your object graph. However, for complex object
* graphs, or for those that don't support deep cloning this can
* be a simple alternative implementation. Of course all the objects
* must be {@code Serializable}.</p>
*
* @param <T> the type of the object involved
* @param object the {@code Serializable} object to clone
* @return the cloned object
* @throws SerializationException (runtime) if the serialization fails
*/
public static <T extends Serializable> T clone(final T object) {
if (object == null) {
return null;
}
final byte[] objectData = serialize(object);
final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais,
object.getClass().getClassLoader())) {
/*
* when we serialize and deserialize an object,
* it is reasonable to assume the deserialized object
* is of the same type as the original serialized object
*/
@SuppressWarnings("unchecked") // see above
final T readObject = (T) in.readObject();
return readObject;
} catch (final ClassNotFoundException ex) {
throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
} catch (final IOException ex) {
throw new SerializationException("IOException while reading or closing cloned object data", ex);
}
}
/**
* Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
* implement {@link Serializable}.
*
* @param <T>
* the type of the object involved
* @param msg
* the object to roundtrip
* @return the serialized and deserialized object
* @since 3.3
*/
@SuppressWarnings("unchecked") // OK, because we serialized a type `T`
public static <T extends Serializable> T roundtrip(final T msg) {
return (T) deserialize(serialize(msg));
}
// Serialize
//-----------------------------------------------------------------------
/**
* <p>Serializes an {@code Object} to the specified stream.</p>
*
* <p>The stream will be closed once the object is written.
* This avoids the need for a finally clause, and maybe also exception
* handling, in the application code.</p>
*
* <p>The stream passed in is not buffered internally within this method.
* This is the responsibility of your application if desired.</p>
*
* @param obj the object to serialize to bytes, may be null
* @param outputStream the stream to write to, must not be null
* @throws IllegalArgumentException if {@code outputStream} is {@code null}
* @throws SerializationException (runtime) if the serialization fails
*/
public static void serialize(final Serializable obj, final OutputStream outputStream) {
Validate.isTrue(outputStream != null, "The OutputStream must not be null");
try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
out.writeObject(obj);
} catch (final IOException ex) {
throw new SerializationException(ex);
}
}
/**
* <p>Serializes an {@code Object} to a byte array for
* storage/serialization.</p>
*
* @param obj the object to serialize to bytes
* @return a byte[] with the converted Serializable
* @throws SerializationException (runtime) if the serialization fails
*/
public static byte[] serialize(final Serializable obj) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
serialize(obj, baos);
return baos.toByteArray();
}
// Deserialize
//-----------------------------------------------------------------------
/**
* <p>
* Deserializes an {@code Object} from the specified stream.
* </p>
*
* <p>
* The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
* exception handling, in the application code.
* </p>
*
* <p>
* The stream passed in is not buffered internally within this method. This is the responsibility of your
* application if desired.
* </p>
*
* <p>
* If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
* Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
* Note that in both cases, the ClassCastException is in the call site, not in this method.
* </p>
*
* @param <T> the object type to be deserialized
* @param inputStream
* the serialized object input stream, must not be null
* @return the deserialized object
* @throws IllegalArgumentException
* if {@code inputStream} is {@code null}
* @throws SerializationException
* (runtime) if the serialization fails
*/
public static <T> T deserialize(final InputStream inputStream) {
Validate.isTrue(inputStream != null, "The InputStream must not be null");
try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
@SuppressWarnings("unchecked")
final T obj = (T) in.readObject();
return obj;
} catch (final ClassNotFoundException | IOException ex) {
throw new SerializationException(ex);
}
}
/**
* <p>
* Deserializes a single {@code Object} from an array of bytes.
* </p>
*
* <p>
* If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
* Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
* Note that in both cases, the ClassCastException is in the call site, not in this method.
* </p>
*
* @param <T> the object type to be deserialized
* @param objectData
* the serialized object, must not be null
* @return the deserialized object
* @throws IllegalArgumentException
* if {@code objectData} is {@code null}
* @throws SerializationException
* (runtime) if the serialization fails
*/
public static <T> T deserialize(final byte[] objectData) {
Validate.isTrue(objectData != null, "The byte[] must not be null");
return deserialize(new ByteArrayInputStream(objectData));
}
/**
* <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
* that uses a custom <code>ClassLoader</code> to resolve a class.
* If the specified <code>ClassLoader</code> is not able to resolve the class,
* the context classloader of the current thread will be used.
* This way, the standard deserialization work also in web-application
* containers and application servers, no matter in which of the
* <code>ClassLoader</code> the particular class that encapsulates
* serialization/deserialization lives. </p>
*
* <p>For more in-depth information about the problem for which this
* class here is a workaround, see the JIRA issue LANG-626. </p>
*/
static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
private static final Map<String, Class<?>> primitiveTypes =
new HashMap<>();
static {
primitiveTypes.put("byte", byte.class);
primitiveTypes.put("short", short.class);
primitiveTypes.put("int", int.class);
primitiveTypes.put("long", long.class);
primitiveTypes.put("float", float.class);
primitiveTypes.put("double", double.class);
primitiveTypes.put("boolean", boolean.class);
primitiveTypes.put("char", char.class);
primitiveTypes.put("void", void.class);
}
private final ClassLoader classLoader;
/**
* Constructor.
* @param in The <code>InputStream</code>.
* @param classLoader classloader to use
* @throws IOException if an I/O error occurs while reading stream header.
* @see java.io.ObjectInputStream
*/
ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
}
/**
* Overridden version that uses the parameterized <code>ClassLoader</code> or the <code>ClassLoader</code>
* of the current <code>Thread</code> to resolve the class.
* @param desc An instance of class <code>ObjectStreamClass</code>.
* @return A <code>Class</code> object corresponding to <code>desc</code>.
* @throws IOException Any of the usual Input/Output exceptions.
* @throws ClassNotFoundException If class of a serialized object cannot be found.
*/
@Override
protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
final String name = desc.getName();
try {
return Class.forName(name, false, classLoader);
} catch (final ClassNotFoundException ex) {
try {
return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
} catch (final ClassNotFoundException cnfe) {
final Class<?> cls = primitiveTypes.get(name);
if (cls != null) {
return cls;
}
throw cnfe;
}
}
}
}
}
原创不易,如需转载,请注明出处@author Davince!