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


基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01