声纳:由于调用方法的返回值,可能出现空指针解引用。

huangapple go评论82阅读模式
英文:

Sonar : Possible null pointer dereference due to return value of called method

问题

if (response != null && response.getBody() != null && response.getStatusCode() == HttpStatus.OK) {
    return new BigDecimal(response.getBody());
}

我在上面的代码中因为调用方法的返回值可能为 null 而出现了可能的空指针解引用问题。

请问有人可以告诉我确切的问题是什么,以及为什么会是个问题呢?

response.getBody() // 返回一个字符串值

提前谢谢!如果需要任何其他细节,请告知。

英文:
if (response != null && response.getBody() != null && response.getStatusCode() == HttpStatus.OK) {
		return new BigDecimal(response.getBody());
}

I am getting possible null pointer dereference due to return value of called method on above code.

Can someone please let me know the exact issue and why it's an issue?

response.getBody() // returns a string value

Thanks in advance! Please let me know if any other details are needed.

答案1

得分: 4

声纳不知道连续调用 getBody() 会返回相同的值。

因此,从静态分析器的角度来看,第二次调用有可能返回 null

我建议将内容分配给一个本地变量,只调用一次获取器。这里 是来自声纳社区的参考,有人将此行为报告为错误并收到了类似的回应。

实际上,静态分析器无法证明这两个调用将返回相同的值,除非 response 是最终的不可变类型。我尝试过的静态分析器都没有办法去尝试证明这一点。

英文:

Sonar does not know that the two consecutive calls to getBody() will return the same value.

So, it is really possible, from the point of view of a static analyzer, that the second call returns null.

I'd recommend assigning the body to a local variable, and calling the getter only once. Here is a reference from Sonar community, where someone reported this behavior as bug and received a similar response.

A static analyzer actually cannot prove that the two calls will return the same value, unless response is of a final and immutable type. And no static analyzer I've tried yet goes to the length of trying to prove that.

huangapple
  • 本文由 发表于 2020年10月2日 19:25:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64170732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定