gpt4 book ai didi

java - Sonar 严重违规 - 对先前取消引用的值进行空检查

转载 作者:搜寻专家 更新时间:2023-10-31 08:19:38 25 4
gpt4 key购买 nike

对于我的一个测试类中的以下代码,Sonar 向我抛出严重违规 - 正确性 - 先前取消引用的值的 Nullcheck

 if (testLst != null && !testLst.isEmpty()) {
for (Test test : testLst) {
if (test.getName().equalsIgnoreCase("TEST")) {
// do blah
}

有人可以阐明我在这里做错了什么吗?

编辑:这里的一个答案表明这是因为我之前可以访问变量,所以空检查是多余的。但事实并非如此。这是空检查之前的代码行。

 testLst = myTest.getValues(); //I am basically populating the array by doing a get, but I am not accessing the list itself by doing a get on it directly - like testLst.get()
if (testLst != null && !testLst.isEmpty()) {
for (Test test : testLst) {
if (test.getName().equalsIgnoreCase("TEST")) {
// do blah
}

最佳答案

当您检查变量的值是否为 null(在本例中为 testLst)而您之前已经访问过该变量时,会显示此消息。不需要进行 null 检查,因为如果值为 null,则会抛出 NullPointerException

示例:

testLst.remove(something);
if (testLst != null && !testLst.isEmpty()) {
for (Test test : testLst) {
if (test.getName().equalsIgnoreCase("TEST")) {
// do blah
}

检查 testLst != null 是多余的,因为在程序到达 if 语句时,testLst 不能为 null,否则之前的语句 testLst.remove(something) 会抛出一个 NullPointerException。在这种情况下,您应该在访问 testLst 之前放置 null 检查,放在它可以为 null 的地方:

if(testLst != null) {
testLst.remove(something);
if (!testLst.isEmpty()) {
for (Test test : testLst) {
if (test.getName().equalsIgnoreCase("TEST")) {
// do blah
}

关于java - Sonar 严重违规 - 对先前取消引用的值进行空检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26722528/

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