编程语言
首页 > 编程语言> > Java:为什么不将clone()用于防御性复制?

Java:为什么不将clone()用于防御性复制?

作者:互联网

在Effective Java(第7章)中,它说

Note also that we did not use Date’s clone method to make the defensive copies. 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. Such a subclass could, for example, record a reference to each instance in a private static list at the time of its creation and allow the attacker to access this list. This would give the attacker free reign over all instances. To prevent this sort of attack, do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties.

我不太明白它的解释.为什么clone()不返回Date对象?实例如何是不可信的子类?

解决方法:

考虑以下代码:

public class MaliciousDate extends Date { /** malicious code here **/ }

public class SomeClass {
    public static void main(String[] args) {
        MaliciousDate someDate = new MaliciousDate();
        Date copyOfMaliciousDate = someDate;
        Date anotherDate = copyOfMaliciousDate.clone();
    }
}

由于copyOfMaliciousDate的类型为Date,您可以调用clone()并返回Date对象,但在copyOfMaliciousDate上调用clone会执行在MaliciousDate类中编写的代码,因为copyOfMaliciousDate中存储的实例是MaliciousDate.

标签:java,effective-java
来源: https://codeday.me/bug/20190609/1205311.html