FindBugs - 与 null 的冗余比较
我遇到以下代码的 findbugs 错误,
if( obj instanceof CustomerData )
{
CustomerData customerData = (CustomerData)obj;
if (customerData == null)
{
errors.reject("Error", "Null data received");
}
}
错误描述:
obj 的冗余 nullcheck,已知
该方法 在(包和方法名称,由于安全违规,我已删除)中为非空包含针对常量 null 的已知非空值的冗余检查。
请让我知道这里有什么错误。
I am having findbugs error for the below code,
if( obj instanceof CustomerData )
{
CustomerData customerData = (CustomerData)obj;
if (customerData == null)
{
errors.reject("Error", "Null data received");
}
}
Error Desc:
Redundant nullcheck of obj, which is known to be non-null in (Package and Method name, I have removed due to security violation)
This method contains a redundant check of a known non-null value against the constant null.
Please let me know what is the error in here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果参数为
null
,则instanceof
返回 false。所以你不需要再做一次检查。instanceof
returns false if the argument isnull
. So you don't need another check.我在下面添加了内联注释...
根据 this,<对于
null
实例,code>instanceof 返回false
。I've added comments inline below...
According to this,
instanceof
returnsfalse
, for anull
instance.显然,在该特定检查的上下文中,
obj
不能为 null。 Findbugs 可以告诉您,并警告您删除多余的检查。除非您向我们提供声明/定义obj
的源代码,否则我们无法为您提供更多帮助。也就是说,Findbugs 错误/警告不一定是问题。在这种情况下,例如,如果您觉得将来可能有必要进行检查,您可以忽略该警告。一种常见的情况是在测试过程中,您对输入对象进行硬编码以测试特定的代码路径,但为了安全起见,您仍然需要在生产中进行空检查。
编辑(在问题编辑之后):
嗯,
null instanceof
始终为 false,因此代码中的instanceof
条件确保obj
不能为空。在这种情况下,您可能想要删除空检查 - 这是多余的,Findbugs 很好地指出了这一点......Apparently
obj
cannot be null in the context of that particular check. Findbugs can tell, and warns you to remove the redudant check. Unless you provide us with the source code whereobj
is declared/defined we cannot help you more.That said, Findbugs errors/warnings are not necessarily a problem. In this case, for example, if you feel that the check may be necessary in the future, you may just ignore the warning. A common case would be during testing where you hardcode input objects to test a specific code path, but you still need the null-check in production for safety.
EDIT (Following the question edit):
Well,
null instanceof <Whatever>
is always false, so theinstanceof
conditional in your code ensures thatobj
cannot be null. In this case you will probably want to remove the null-check - it's superfluous and Findbugs did well to point it out...