Java:为什么不将clone()用于防御性复制? [英] Java: Why shouldn't clone() be used for defensive copying?

查看:131
本文介绍了Java:为什么不将clone()用于防御性复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Effective Java (Chapter 7), it says


另请注意,我们没有使用Date的克隆方法来制作防御性副本。因为Date是非最终的,所以不能保证clone方法返回一个类为java.util.Date的对象:它可能返回一个专门为恶意恶作剧设计的不可信子类的实例。例如,这样的子类可以在创建私有静态列表时记录对每个实例的引用,并允许攻击者访问该列表。这将使攻击者在所有实例中自由统治。为了防止这种攻击,请不要使用clone方法制作一个参数的防御性副本,该参数的类型可由不信任方进行子类化。

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对象?该实例如何是不可信的子类?

I don't quite understand its explanation. Why does clone() not return a Date object? How can the instance be of untrusted subclass?

推荐答案

考虑以下代码:

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 类型为日期,您可以调用 clone(),它将返回 Date object,但在 copyOfMaliciousDate 上调用 clone 执行 MaliciousDate 类,因为存储在 copyOfMaliciousDate 中的实例 MaliciousDate

Since copyOfMaliciousDate is of type Date, you can call clone() and it will return a Date object, but calling clone on copyOfMaliciousDate executes the code written in the MaliciousDate class because the instance stored in copyOfMaliciousDate is a MaliciousDate.

这篇关于Java:为什么不将clone()用于防御性复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆