Sonar Violation: Security - Array is stored directly(声纳违规:安全 - 阵列直接存储)
问题描述
存在声纳违规:
声纳违规:安全 - 阵列直接存储
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.
这篇关于声纳违规:安全 - 阵列直接存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声纳违规:安全 - 阵列直接存储


基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01