声纳违规:安全 - 阵列直接存储
存在声纳违规:
声纳违规:安全 - 阵列直接存储
public void setMyArray(String[] myArray) {
this.myArray = myArray;
}
解决方案:
public void setMyArray(String[] newMyArray) {
if(newMyArray == null) {
this.myArray = new String[0];
} else {
this.myArray = Arrays.copyOf(newMyArray, newMyArray.length);
}
}
但我想知道为什么?
推荐答案
抱怨您存储的数组与调用者持有的数组相同.也就是说,如果调用者随后修改了这个数组,那么存储在对象中的数组(以及对象本身)将会改变.
It's complaining that the array you're storing is the same array that is held by the caller. That is, if the caller subsequently modifies this array, the array stored in the object (and hence the object itself) will change.
解决方案是在对象被传递时在对象内进行复制.这称为防御性复制.对集合的后续修改不会影响存储在对象中的数组.
The solution is to make a copy within the object when it gets passed. This is called defensive copying. A subsequent modification of the collection won't affect the array stored within the object.
通常在返回集合时执行此操作也是一个好习惯(例如,在相应的 getMyArray()
调用中).否则接收者可能会执行修改并影响存储的实例.
It's also good practice to normally do this when returning a collection (e.g. in a corresponding getMyArray()
call). Otherwise the receiver could perform a modification and affect the stored instance.
请注意,这显然适用于所有可变集合(实际上是所有可变对象)——不仅仅是数组.另请注意,这会对性能产生影响,需要与其他问题一起评估.
Note that this obviously applies to all mutable collections (and in fact all mutable objects) - not just arrays. Note also that this has a performance impact which needs to be assessed alongside other concerns.
相关文章