您认为解决以下问题时的最佳实践是:
MyClass myVariable = null;
if ( ..condition 1.. ) {
myVariable = new MyClass(1);
} else if ( ..condition 2.. ) {
myVariable = new MyClass(2);
}
myVariable.execute();
哪一个是解决警告的好方法?
最后的
其他
final MyClass myVariable; .... } else { // let's say this assert makes sense here Assert.fail("This should not happen"); }
抛出
RuntimeException
final MyClass myVariable; .... } else { throw new RuntimeException("Some message, like <should not happen>"); }
检查 NPE
final MyClass myVariable; .... if (myVariable != null) { myVariable.execute(); }
还有其他想法吗?
提前致谢!
最佳答案
这取决于条件 1 或条件 2 是否必须始终为真。
如果条件 2 与条件 1 完全相反,您可以替换 else if ( ..condition 2.. )
与 else
并解决您的问题。
如果不是,并且条件 1 和条件 2 都为假,则表明输入无效,我会抛出异常。
如果两个条件都为假的场景是有效的场景,我会检查 myVariable
调用 myVariable.execute()
之前不为空.
关于java - 避免 "Potential null pointer access",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28211273/