Java 中存在基础类型和引用类型。Java 的赋值都是传值的
在此基础上,「对象的拷贝」可分为两种情况
Java 中所有的对象都是继承自 java.lang.Object。Object 对象中提供了一个 protected 类型的 clone 方法。
protected native Object clone()
throws CloneNotSupportedException;
Object#clone() 方法是 native 的,所以不需要我们来实现。需要注意的是,clone 方法是 protected 的,这意味着 clone 方法只能在 java.lang 包或者其子类可见。
如果我们想要在一个程序中调用某个对象的 clone 方法则是不可以的。因为 clone 方法是定义在 Object 中的,该对象并没有对外可见的 clone 方法。
在上文中提到,Object#clone() 方法是 protected 的,我们不能直接在程序中对一个对象调用 clone 方法。
JDK 推荐「实现 Cloneable 接口并重写 clone 方法(可使用 public 修饰符)来实现属性的拷贝」。
package java.lang;
/**
* 此处给出 Cloneable 的部分注释
* A class implements the Cloneable interface to
* indicate to the java.lang.Object#clone() method that it
* is legal for that method to make a
* field-for-field copy of instances of that class.
*
* Invoking Object's clone method on an instance that does not implement the
* Cloneable interface results in the exception
* CloneNotSupportedException being thrown.
*
* By convention, classes that implement this interface should override
* Object.clone (which is protected) with a public method.
*/
public interface Cloneable {
}
阅读 Cloneable 源码,有如下结论
参照《Effective Java》中「第13条 谨慎地重写 clone 方法」
Cloneable 接口的目的是作为一个 mixin 接口,约定如果一个类实现了 Cloneable 接口,那么 Object 的 clone 方法将返回该对象的逐个属性(field-by-field)拷贝(浅拷贝);否则会抛出 CloneNotSupportedException 异常。
上面第1、2点,可用下面的伪代码描述。
protected Object clone throws CloneNotSupportedException {
if(!(this instanceof Cloneable)){
throw new CloneNotSupportedException("Class" + getClass().getName() + "doesn't implement Cloneable");
}
return internalClone();
}
/**
* Native Helper method for cloning.
*/
private native Object internalClone();
参考 Cloneable 接口的源码注释部分,如果一个类实现了 Cloneable 接口,那么 Object 的 clone 方法将返回该对象的逐个属性(field-by-field)拷贝,这里的拷贝是浅拷贝。
下面结合一个示例加以说明。
@Data
class Address implements Cloneable{
private String name;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
@Data
class CustomerUser implements Cloneable{
private String firstName;
private String lastName;
private Address address;
private String[] cars;
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
testShallowCopy();
}
public static void testShallowCopy() throws CloneNotSupportedException {
Address address= new Address();
address.setName("北京天安门");
CustomerUser customerUser = new CustomerUser();
customerUser.setAddress(address);
customerUser.setLastName("李");
customerUser.setFirstName("雷");
String[] cars = new String[]{"别克","路虎"};
customerUser.setCars(cars);
//浅拷贝
CustomerUser customerUserCopy =(CustomerUser) customerUser.clone();
customerUserCopy.setFirstName("梅梅");
customerUserCopy.setLastName("韩");
customerUserCopy.getAddress().setName("北京颐和园");
customerUserCopy.getCars()[0]="奥迪";
System.out.println("customerUser: " + JSONUtil.toJsonStr(customerUser));
System.out.println("customerUserCopy: " + JSONUtil.toJsonStr(customerUserCopy));
}
}
customerUser: {"lastName":"李","address":{"name":"北京颐和园"},"firstName":"雷","cars":["奥迪","路虎"]}
customerUserCopy: {"lastName":"韩","address":{"name":"北京颐和园"},"firstName":"梅梅","cars":["奥迪","路虎"]}
实现深拷贝有两种方式,「序列化对象方式」和「二次调用 clone 方式」
下面,在「浅拷贝」章节示例的基础上,使用「二次调用 clone 方式」实现深拷贝。
@Data
class CustomerUser implements Cloneable{
private String firstName;
private String lastName;
private Address address;
private String[] cars;
@Override
public Object clone() throws CloneNotSupportedException{
CustomerUser customerUserDeepCopy = (CustomerUser) super.clone();
//二次调用clone方法
customerUserDeepCopy.address = (Address) address.clone();
customerUserDeepCopy.cars = cars.clone();
return customerUserDeepCopy;
}
}
customerUser: {"lastName":"李","address":{"name":"北京天安门"},"firstName":"雷","cars":["别克","路虎"]}
customerUserCopy: {"lastName":"韩","address":{"name":"北京颐和园"},"firstName":"梅梅","cars":["奥迪","路虎"]}
在介绍 clone 方法的基础上,引出对「创建对象的4种方法」,「clone和new的效率对比」等问题的介绍。
创建对象的 4 种方法如下
以上 4 种方式,都可以创建一个 Java 对象,实现机制上有如下区别
使用 clone 创建对象,直接在内存中进行数据块的拷贝。这是否意味着 clone 方法的效率更高呢?
答案并不是,JVM 的开发者意识到通过 new 方式来生成对象的方式,使用的更加普遍,所以对于利用 new 操作生成对象进行了优化。
下面编写一个测试用例,用 clone 和 new 两种方式来创建 10000 * 1000 个对象,测试对应的耗时。
public class Bean implements Cloneable {
private String name;
public Bean(String name) {
this.name = name;
}
@Override
protected Bean clone() throws CloneNotSupportedException {
return (Bean) super.clone();
}
}
public class TestClass {
private static final int COUNT = 10000 * 1000;
public static void main(String[] args) throws CloneNotSupportedException {
long s1 = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) {
Bean bean = new Bean("ylWang");
}
long s2 = System.currentTimeMillis();
Bean bean = new Bean("ylWang");
for (int i = 0; i < COUNT; i++) {
Bean b = bean.clone();
}
long s3 = System.currentTimeMillis();
System.out.println("new = " + (s2 - s1));
System.out.println("clone = " + (s3 - s2));
}
}
程序输出如下。
new = 7
clone = 83
可以看到,创建 10000 * 1000 个对象,使用 new 方法的耗时,只有 clone 方式的 1/10,即 new 方式创建对象的效率更高。
但是,若构造函数中有一些耗时操作,则 new 方式创建对象的效率会受到构造函数性能的影响。如下代码,在构造函数中添加字符串截取的耗时操作。
public class Bean implements Cloneable {
private String name;
private String firstSign;//获取名字首字母
public Bean(String name) {
this.name = name;
if (name.length() != 0) {
firstSign = name.substring(0, 1);
firstSign += "abc";
}
}
@Override
protected Bean clone() throws CloneNotSupportedException {
return (Bean) super.clone();
}
}
此时,再执行测试用例,创建 10000 * 1000 个对象,程序输出如下,使用 new 方法的耗时,就远大于 clone 方式了。
new = 297
clone = 60
最后,对「clone 和 new 的效率对比」给出结论
基于上述结论,在上文「深拷贝」章节中,可对深拷贝功能的实现进行优化,不要调用 clone 方法来创建对象,改为直接调用构造函数来实现。
@Data
class Address implements Cloneable{
private String name;
Address(Address address){
this.name=address.name;
}
}
@Data
class CustomerUser implements Cloneable{
private String firstName;
private String lastName;
private Address address;
private String[] cars;
CustUserDeep(CustUserDeep custUserDeep){
this.firstName = custUserDeep.firstName;
this.lastName = custUserDeep.lastName;
this.cars = custUserDeep.getCars().clone();
this.address = new Address(custUserDeep.getAddress());
}
}
作者:变速风声
链接:https://juejin.cn/post/7103385559623532558
留言与评论(共有 0 条评论) “” |