2011-07-13 44 views
5

我具有用於下面的代碼FindBugs的錯誤,的FindBugs - 冗餘比較爲null

if(obj instanceof CustomerData) 
{ 
    CustomerData customerData = (CustomerData)obj; 

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

錯誤說明:obj的

冗餘nullcheck,這是衆所周知的是在非空(包和方法名稱,由於違反安全原因我已刪除)

此方法包含對常量null的已知非空值的冗餘檢查。

請讓我知道這裏有什麼錯誤。

+1

從錯誤,我會假設'CustomerData customerData =(CustomerData)obj;'會拋出如果'obj'爲空,那麼'if(customerData == null)'是多餘的(或者,上面的代碼清楚地表明'obj'是'not null'),這是一個例外。 – forsvarir

+0

我添加了「if condition」代碼。 – Srinivasan

回答

11

instanceof返回false如果參數是null。所以你不需要再次檢查。

3

我已經添加評論直列下面...

thisinstanceof回報false,對於null實例。

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可以告訴,並警告您刪除redudant檢查。除非您向我們提供聲明/定義obj的源代碼,否則我們無法爲您提供更多幫助。

這就是說,Findbugs錯誤/警告不一定是一個問題。例如,在這種情況下,如果您覺得將來可能需要支票,您可以忽略該警告。一個常見的情況是在測試過程中硬編碼輸入對象以測試特定代碼路徑,但您仍然需要生產中的空檢查以確保安全。

編輯(以下問題編輯):

好,null instanceof <Whatever>永遠是假的,所以instanceof有條件在你的代碼確保obj不能爲空。在這種情況下,你可能想刪除空檢查 - 這是多餘的,Findbugs很好地指出它...