gpt4 book ai didi

java - 为什么将私有(private)字段的副本声明为 `final`

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

Efficient Java 约书亚布洛赫写道:

Note that a nonzero-length array is always mutable, so it is wrong for a class to have a public static final array field, or an accessor that returns such a field. If a class has such a field or accessor, clients will be able to modify the contents of the array. This is a frequent source of security holes:

// Potential security hole!
public static final Thing[] VALUES = { ... };

Beware of the fact that many IDEs generate accessors that return references to private array fields, resulting in exactly this problem. There are two ways to fix the problem. You can make the public array private and add a public immutable list:

private static final Thing[] PRIVATE_VALUES = { ... };
public static final List<Thing> VALUES =
Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

Alternatively, you can make the array private and add a public method that returns a copy of a private array:

private static final Thing[] PRIVATE_VALUES = { ... };
public static final Thing[] values() {
return PRIVATE_VALUES.clone();
}

我的问题是:

  • 为什么要返回一个 final 变量 - 如果它只是一个副本?


毕竟,在用户想要修改它(供她/他自己使用)的情况下,我们实际上是在强制她/他创建另一个非最终副本,这是没有意义的。

最佳答案

Arrays.asList 包装原始数组。它不会复制数据。 Collections.unmodifiableList 也包装原始列表而不是复制数据。

这就是您返回 unmodifiableList 包装器的原因,否则,对 Arrays.asList 返回的列表所做的更改将写入原始私有(private)数组。

关于java - 为什么将私有(private)字段的副本声明为 `final`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577079/

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