gpt4 book ai didi

java - 如果输入参数无效,如何在构造函数中制作防御性副本

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

在 Josh Bloch 的优秀著作中 Effective Java在第 39 项下,他说:

"[D]efensive copies are made before checking the validity of the parameters, and the validity check is performed on the copies rather than on the originals."

给出的例子如下:

public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());

if(this.start.compareTo(this.end) > 0)
throw new IllegalArgumentException("...");
}
}

在防御副本之后进行有效性检查的问题是无效参数可能导致副本创建失败。例如,如果您为 startend 传递一个 null,上面的类将抛出一个 NullPointerException

如果我在防御性副本之前移动有效性检查,我很容易受到检查时间/使用时间攻击,Bloch 将其引用为首先执行防御性副本的原因。

我的问题是如何解决这个问题?我不敢相信我是第一个在一本读得很好的书中看到这个问题的人(尽管这本书的勘误表没有说明任何问题),所以也许我只是遗漏了一些东西。

最佳答案

正如其他人所说,您在复制参数之前检查 null

If I move the validity check before the defensive copy, I am vulnerable to the time-of-check/time-of-use attack that Bloch cites as the reason for doing the defensive copy first.

不,黑客无法将对实际实例的引用更改为空引用,反之亦然。复制是为了避免从另一个线程更改参数的内部状态。

关于java - 如果输入参数无效,如何在构造函数中制作防御性副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7277866/

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