简体   繁体   English

了解非最终类的克隆方法

[英]Understanding clone method for non-final classes

I'm reading J. Bloch's effective java and now I'm at the section 39 (making defensive copy). 我正在阅读J. Bloch的有效Java,现在在第39节(制作防御性副本)。 He mentioned that it's not good to make defensive copies through the clone method, because: 他提到通过clone方法制作防御性副本不是很好,因为:

Note also that we did not use Date's clone method to make the defensive copies. 还要注意,我们没有使用Date的clone方法制作防御副本。 Because Date is nonfinal, the clone method is not guaranteed to return an object whose class is java.util.Date: it could return an instance of an untrusted subclass specifically designed for malicious mischief. 因为Date是非最终的,所以不能 保证 clone方法返回一个类为java.util.Date的对象:它可能返回专门为恶意恶作剧而设计的不受信任子类的实例

The emphasized statement is not apparent to me. 强调的陈述对我来说并不明显。 Actually, let's consut with the javadocs . 实际上,让我们咨询一下javadocs There was no any reference about creating subclasses. 没有关于创建子类的任何参考。 The only we can be sure about is this: 我们唯一可以确定的是:

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. 字段的内容本身不会被克隆。

So why did J. Bloch say that it could create the subclass ? 那么,J。Bloch为什么说可以创建子类呢? Couldn't you explain how it implies from the javadoc (I can't see that on my own). 您无法从javadoc解释它的含义(我自己看不到)。

It is implicit in the Javadocs quote: The class of "this" object can be a subclass of the declared type of the variable referencing the object (due to polymorphism). 它在Javadocs引用中是隐含的:“ this”对象的类可以是引用该对象的变量的声明类型的子类(由于多态性)。 The clone method is protected so it can be invoked in a subclass of a certain class. clone方法受保护,因此可以在某个类的子类中调用它。

public class Test {
    public static void main(String[] args) throws Exception {
        Foo foo = new Bar();
        Foo copyOfFoo = createCopyOfFoo(foo);
        System.out.println(copyOfFoo);
    }


    private static Foo createCopyOfFoo(Foo foo) throws CloneNotSupportedException {
        Foo clone = (Foo) foo.clone();
        return clone;
    }
}

class Foo implements Cloneable {
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Bar extends Foo {
    private int x = 1;

    @Override
    public String toString() {
        return "Bar [x=" + x + "]";
    }
}

Output: 输出:

Bar [x=1] 条[x = 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM