【问题标题】:Why do I get a "Possible null pointer dereference" warning?为什么我会收到“可能的空指针取消引用”警告?
【发布时间】:2012-04-25 08:57:36
【问题描述】:

为什么 FindBugs 会向我提出以下警告:Possible null pointer dereference

current = myService.getCategoryParent(current);
if (current != null) { // The warning appears here

我不明白如何针对 null 测试变量可以取消引用它。

【问题讨论】:

  • @MichaelBorgwardt 这是一个自定义的Category
  • 当前是否在此 if 语句之后/之外使用?
  • @BeRecursive: 上面一行用到了。
  • @T.J.Crowder 啊是的,这是有道理的

标签: java nullpointerexception findbugs


【解决方案1】:

我怀疑错误/警告实际上位于您指定的行上方

//                   here ------------v
current = myService.getCategoryParent(current);
if (current != null) {

【讨论】:

  • Sonar 在第二行报告警告,但我添加了上面的行只是为了确定,因为我也有疑问......如果是这样,那么警告是什么?
  • @Matthieu:大概是担心getCategoryParent 会取消引用传入的参数? getCategoryParent!null 支票吗?
  • 是的,有!=null 支票。但是getCategoryParent 可以返回null,是这样吗?
  • @Matthieu: getCategoryParent 返回null 不是问题,因为您在调用它之后就获得了null 检查。作为一项实验,我建议在您引用的两行之间放置 10 个 System.out.println("foo"); 行,然后再次运行 FindBugs,以防在其行号报告中出现双簧管(一个错误)。只是为了缩小实际警告的范围。
猜你喜欢
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-03-03
  • 2015-01-13
  • 2013-06-13
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多