FindBugs -多余的null比较



我有以下代码的findbugs错误,

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

错误Desc:

obj的冗余null检查,已知在(包和方法名,由于安全违规,我已删除)中为非空

此方法包含对已知非空值与常量null的冗余检查。

如果参数为null,则instanceof返回false。所以你不需要再检查了

我在下面添加了内联注释…

据此,对于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");
    }
}

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

也就是说,Findbugs错误/警告不一定是问题。例如,在这种情况下,如果您觉得将来可能需要检查,则可以忽略警告。常见的情况是,在测试期间,您硬编码输入对象以测试特定的代码路径,但为了安全起见,您仍然需要在生产中使用null检查。

EDIT(在问题编辑之后):

好吧,null instanceof <Whatever>总是假的,所以你代码中的instanceof条件确保obj不能为空。在这种情况下,您可能想要删除空检查—它是多余的,Findbugs很好地指出了这一点…

最新更新