问题描述
声纳违规行为:
声纳违规:安全 - 数据直接存储
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.
这篇关于声纳违规:安全 - 数组直接存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!