FindBugs - 多余的与null比较

5
我在以下代码中遇到了FindBugs错误:
if( obj instanceof CustomerData )
{
    CustomerData customerData = (CustomerData)obj;

    if (customerData == null) 
    {
        errors.reject("Error", "Null data received");
    }
}

错误描述:

在(由于安全问题我已删除包名和方法名)中,对已知非空的obj进行了冗余的nullcheck。

该方法对已知的非空值进行了与常量null的冗余检查。

请告诉我这里的错误是什么。


1
从错误来看,我会认为如果obj为空,CustomerData customerData = (CustomerData)obj;会抛出异常,因此这个if (customerData == null)是多余的(或者说,上面的代码已经明确了obj不为空)。 - forsvarir
我已经添加了“if条件”代码。 - Srinivasan
3个回答

12

instanceof会在参数为null时返回false。因此您不需要再进行其他检查。


4
根据这里的说法,对于一个null实例,instanceof返回false。我已经在下面添加了注释...
if( obj instanceof CustomerData )
{

    /* To get here, obj must be a non-null instance of CustomerData,
     * so the following cast will always succeed and result in a non-null
     * customerData
     */

    CustomerData customerData = (CustomerData)obj;

    /* customerData cannot be null because of the conditions above, so
     * this check is pointless (it'll never be triggered
     */

    if (customerData == null) 
    {
        /* This line cannot be reached, because of the conditions above */
        errors.reject("Error", "Null data received");
    }
}

1

显然,在该特定检查的上下文中,obj 不能为空。 Findbugs 可以检测到,并警告您删除多余的检查。除非您向我们提供了声明/定义 obj 的源代码,否则我们无法为您提供更多帮助。

话虽如此,Findbugs 的错误/警告并不一定是问题。例如,在这种情况下,如果您认为将来可能需要该检查,您可以忽略该警告。一个常见案例是在测试期间,您硬编码输入对象以测试特定的代码路径,但您仍然需要在生产中进行空值检查以确保安全性。

编辑(根据问题编辑):

嗯,null instanceof <Whatever> 总是 false,因此您代码中的 instanceof 条件语句确保了 obj 不为空。 在这种情况下,您可能希望删除空值检查-它是多余的,并且 Findbugs 做得很好,指出了这一点...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接