Java的对象克隆分为浅克隆和深克隆。
1. 浅克隆只会复制基本数据类型,引用类型只会复制引用。如下图
Object1与复制体Object2在Object3的复制是复制指针,Object3仅有一个对象,并没有复制。
浅克隆实现主要通过实现Cloneable接口,示例如下
clone方法的本质Object的clone方法
/**
* Creates and returns a copy of this object. The precise meaning
* of "copy" may depend on the class of the object. The general
* intent is that, for any object {@code x}, the expression:
* <blockquote>
* <pre>
* x.clone() != x</pre></blockquote>
* will be true, and that the expression:
* <blockquote>
* <pre>
* x.clone().getClass() == x.getClass()</pre></blockquote>
* will be {@code true}, but these are not absolute requirements.
* While it is typically the case that:
* <blockquote>
* <pre>
* x.clone().equals(x)</pre></blockquote>
* will be {@code true}, this is not an absolute requirement.
* <p>
* By convention, the returned object should be obtained by calling
* {@code super.clone}. If a class and all of its superclasses (except
* {@code Object}) obey this convention, it will be the case that
* {@code x.clone().getClass() == x.getClass()}.
* <p>
* By convention, the object returned by this method should be independent
* of this object (which is being cloned). To achieve this independence,
* it may be necessary to modify one or more fields of the object returned
* by {@code super.clone} before returning it. Typically, this means
* copying any mutable objects that comprise the internal "deep structure"
* of the object being cloned and replacing the references to these
* objects with references to the copies. If a class contains only
* primitive fields or references to immutable objects, then it is usually
* the case that no fields in the object returned by {@code super.clone}
* need to be modified.
* <p>
* The method {@code clone} for class {@code Object} performs a
* specific cloning operation. First, if the class of this object does
* not implement the interface {@code Cloneable}, then a
* {@code CloneNotSupportedException} is thrown. Note that all arrays
* are considered to implement the interface {@code Cloneable} and that
* the return type of the {@code clone} method of an array type {@code T[]}
* is {@code T[]} where T is any reference or primitive type.
* Otherwise, this method creates a new instance of the class of this
* object and initializes all its fields with exactly the contents of
* the corresponding fields of this object, as if by assignment; the
* contents of the fields are not themselves cloned. Thus, this method
* performs a "shallow copy" of this object, not a "deep copy" operation.
* <p>
* The class {@code Object} does not itself implement the interface
* {@code Cloneable}, so calling the {@code clone} method on an object
* whose class is {@code Object} will result in throwing an
* exception at run time.
*
* @return a clone of this instance.
* @throws CloneNotSupportedException if the object's class does not
* support the {@code Cloneable} interface. Subclasses
* that override the {@code clone} method can also
* throw this exception to indicate that an instance cannot
* be cloned.
* @see java.lang.Cloneable
*/
protected native Object clone() throws CloneNotSupportedException;
举例实现
public class Test2 {
@Data
public static class Man implements Cloneable{
private String name;
private int age;
private Woman woman;
@Override
public Man clone() throws CloneNotSupportedException {
return (Man) super.clone();
}
@Override
public String toString() {
return "Man{" +
"name='" + name + '\'' +
", age=" + age +
", woman=" + woman +
'}';
}
}
@Data
public static class Woman implements Cloneable{
private String name;
private int age;
@Override
public Woman clone() throws CloneNotSupportedException {
return (Woman) super.clone();
}
@Override
public String toString() {
return "Woman{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Woman woman = new Woman();
woman.setAge(12);
woman.setName("Lily");
Man man = new Man();
man.setAge(10);
man.setName("Tom");
man.setWoman(woman);
Man man1 = man.clone();
man1.setAge(11);
man1.setName("Jim");
man1.getWoman().setAge(15);
System.out.println(man);
System.out.println(man1);
}
}
输出结果
Man{name='Tom', age=10, woman=Woman{name='Lily', age=15}}
Man{name='Jim', age=11, woman=Woman{name='Lily', age=15}}
可以看出Woman对象仅拷贝指针,修改后克隆与被克隆的对象均会变化。
特别指出String,String是不可变对象引用,只能赋值(赋值是改变指针指向),所以即使修改,只是拨动指针引用。不会对指针的内存地址造成改变,仅指向新内存地址。
2. 深克隆
深克隆需要克隆引用类型的对象
有多种方法比如自己实现new关键字,序列化,反射(实现麻烦)等
2.1. 自定义clone方法
public class Test2 {
@Data
public static class Man implements Cloneable{
private String name;
private int age;
private Woman woman;
@Override
public Man clone() throws CloneNotSupportedException {
Man man = (Man) super.clone();
Woman woman = new Woman();
woman.setAge(man.getWoman().getAge());
woman.setName(man.getWoman().getName());
man.setWoman(woman);
return man;
}
@Override
public String toString() {
return "Man{" +
"name='" + name + '\'' +
", age=" + age +
", woman=" + woman +
'}';
}
}
@Data
public static class Woman implements Cloneable{
private String name;
private int age;
@Override
public Woman clone() throws CloneNotSupportedException {
return (Woman) super.clone();
}
@Override
public String toString() {
return "Woman{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Woman woman = new Woman();
woman.setAge(12);
woman.setName("Lily");
Man man = new Man();
man.setAge(10);
man.setName("Tom");
man.setWoman(woman);
Man man1 = man.clone();
man1.setAge(11);
man1.setName("Jim");
man1.getWoman().setAge(15);
System.out.println(man);
System.out.println(man1);
}
}
此时输出
Man{name='Tom', age=10, woman=Woman{name='Lily', age=12}}
Man{name='Jim', age=11, woman=Woman{name='Lily', age=15}}
因为Woman是new出来的,新建对象分配堆内存空间。实现了引用对象的复制。
还可以深度克隆,克隆man对象,在克隆woman对象。
public class Test2 {
@Data
public static class Man implements Cloneable{
private String name;
private int age;
private Woman woman;
@Override
public Man clone() throws CloneNotSupportedException {
Man man = (Man) super.clone();
//多次克隆
man.woman = woman.clone();
return man;
}
@Override
public String toString() {
return "Man{" +
"name='" + name + '\'' +
", age=" + age +
", woman=" + woman +
'}';
}
}
@Data
public static class Woman implements Cloneable{
private String name;
private int age;
@Override
public Woman clone() throws CloneNotSupportedException {
return (Woman) super.clone();
}
@Override
public String toString() {
return "Woman{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Woman woman = new Woman();
woman.setAge(12);
woman.setName("Lily");
Man man = new Man();
man.setAge(10);
man.setName("Tom");
man.setWoman(woman);
Man man1 = man.clone();
man1.setAge(11);
man1.setName("Jim");
man1.getWoman().setAge(15);
System.out.println(man);
System.out.println(man1);
}
}
2.2. 序列化和反序列化
这种模式常用于对象跨进程,网络的传输
public class Test2 {
@Data
public static class Man implements Serializable {
//显式声明Serializable ID,远程传输尤为重要,决定传输过程的识别
private static final long serialVersionUID = 6666666666666666666L;
private String name;
private int age;
private Woman woman;
//深度复制方法,需要对象及对象所有的对象属性都实现序列化
public Man serializableClone() {
Man man = null;
try {
// 将该对象序列化成流,
// 写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。
// 流对象可以写文件,也可以网络,进程间传输
// RPC框架的实现思路
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
// 将流反序列化成对象
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
man = (Man) ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return man;
}
@Override
public String toString() {
return "Man{" +
"name='" + name + '\'' +
", age=" + age +
", woman=" + woman +
'}';
}
}
@Data
public static class Woman implements Serializable {
private static final long serialVersionUID = 3333333333333333333L;
private String name;
private int age;
@Override
public String toString() {
return "Woman{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
Woman woman = new Woman();
woman.setAge(12);
woman.setName("Lily");
Man man = new Man();
man.setAge(10);
man.setName("Tom");
man.setWoman(woman);
Man man1 = man.serializableClone();
man1.setAge(11);
man1.setName("Jim");
man1.getWoman().setAge(15);
System.out.println(man);
System.out.println(man1);
}
}
结果依旧
Man{name='Tom', age=10, woman=Woman{name='Lily', age=12}}
Man{name='Jim', age=11, woman=Woman{name='Lily', age=15}}
String也是可以序列化的
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
Java语言提供的Cloneable接口和Serializable接口都是标识接口,标识接口中没有任何方法的定义,作用是告诉JRE这些接口的实现类具有某个功能,比如是否支持克隆、是否支持序列化等。
3. 反射
public class Test2 {
@Data
public static class Man {
private String name;
private int age;
private Woman woman;
public Man reflectClone() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//加载类
Class c = this.getClass();
//获取类中的构造方法
Constructor ct = c.getConstructor(new Class[] {});
//在构造方法中传值
Object obj = ct.newInstance(new Object[] {});
//获取所有属性
Field[] f = c.getDeclaredFields();
for(Field field : f) {
String name = field.getName();
//拼接getter setter方法
String firstLetter = name.substring(0, 1).toUpperCase();
String getMethodName = "get"+firstLetter+name.substring(1);
String setMethodName = "set"+firstLetter+name.substring(1);
//得到getter setter方法
Method getMethod = c.getMethod(getMethodName, new Class[] {});
Method setMethod = c.getMethod(setMethodName, new Class[] {field.getType()});
//getter方法获取值
Object value = getMethod.invoke(this, new Object[] {});
System.out.println(value);
//setter方法设置值
setMethod.invoke(obj, new Object[] {value});
}
return (Man) obj;
}
@Override
public String toString() {
return "Man{" +
"name='" + name + '\'' +
", age=" + age +
", woman=" + woman +
'}';
}
}
@Data
public static class Woman {
private String name;
private int age;
@Override
public String toString() {
return "Woman{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
Woman woman = new Woman();
woman.setAge(12);
woman.setName("Lily");
Man man = new Man();
man.setAge(10);
man.setName("Tom");
man.setWoman(woman);
Man man1 = man.reflectClone();
man1.setAge(11);
man1.setName("Jim");
man1.getWoman().setAge(15);
System.out.println(man);
System.out.println(man1);
}
}
结果
Man{name='Tom', age=10, woman=Woman{name='Lily', age=15}}
Man{name='Jim', age=11, woman=Woman{name='Lily', age=15}}
是浅克隆
本质是ct.newInstance(new Object[] {}); set方法,深度克隆实现麻烦(需要判断哪个field是引用对象类型,对这个field反射复制),不推荐。