Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java FindBugs:为什么我得到了NP_NULL_PARAM_DEREF,还有什么更好?_Java_Findbugs - Fatal编程技术网

Java FindBugs:为什么我得到了NP_NULL_PARAM_DEREF,还有什么更好?

Java FindBugs:为什么我得到了NP_NULL_PARAM_DEREF,还有什么更好?,java,findbugs,Java,Findbugs,通过下面的代码,我得到了NP_NULL_PARAM_DEREF:Method调用为非NULL参数传递NULL: public void calledAnywhereIDoNotCare() { //[...] //parameter could be null but shouldn't ever be by logic method(parameter); //FindBugs says the problem is here //[...] } public final R

通过下面的代码,我得到了NP_NULL_PARAM_DEREF:Method调用为非NULL参数传递NULL:

public void calledAnywhereIDoNotCare() {
  //[...]
  //parameter could be null but shouldn't ever be by logic
  method(parameter); //FindBugs says the problem is here
  //[...]
}

public final ReturnType method(final ParameterType parameter) {
  //this method do nothing but simply call anotherMethod()
  return anotherMethod(parameter, false);
}

public final ReturnType anotherMethod(final ParameterType parameter, boolean boolParam) {
  if (parameter == null) {
    //just in case logic is wrong
    throw new NullPointerException("I know it shouldn't be null by logic, but it is null!");
  }
  //do something very usefull
  //[...]
}
所以,我的问题是:为什么我会得到这个NP_NULL_PARAM_DEREF,还有什么变化会更好? 我得到这个是因为声明了参数final吗?还是因为没有捕获NullPointerException?我不想抓住它,它应该在外面的某个地方被抓住。也许我应该声明在CalledAnyWhere IdoNotCare()中抛出NullPointerException

谢谢你的帮助。
TARL

在您的注释中,您写道,由于程序逻辑,参数“可能”为空,但永远不会为空。FindBugs不知道/不理解逻辑。最好的方法是让FindBugs使用edu.umd.cs.FindBugs.annotations.SuppressWarnings注释忽略此方法中的NP_NULL_参数DEREF。请参见

Ok,可以抑制警告。但是为什么我的方法中的参数对于findbugs来说是非空参数呢?遗憾的是findbugs不是很聪明。也许您可以发布CalledAnyWhereIDOntCare()的代码。但它可能无法检测到阻止null的逻辑,因此它会警告您。消除警告的另一种方法是添加“处理”从不存在的空值的代码。但是我会考虑这个错误的做法,或者它是如此聪明以至于它可以确定如果NULL值通过,就抛出一个NPE。如果anotherMethod中的值为parameter为null,请查看仅打印消息时会发生什么情况?