gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:24:15 25 4
gpt4 key购买 nike

在 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();
}
}

因为 copyOfMaliciousDateDate 类型,你可以调用 clone() 并且它会返回一个 Date对象,但在 copyOfMaliciousDate 上调用 clone 会执行在 MaliciousDate 类的 clone() 中编写的代码,因为 <存储在 copyOfMaliciousDate 中的 em>instance 是一个 MaliciousDate

关于Java:为什么不应该将 clone() 用于防御性复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com