- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在 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
类的 clone()
中编写的代码,因为 <存储在 copyOfMaliciousDate
中的 em>instance 是一个 MaliciousDate
。
关于Java:为什么不应该将 clone() 用于防御性复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528850/
我是一名优秀的程序员,十分优秀!