Reputation: 12040
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.
Upvotes: 5
Views: 12974
Reputation: 86333
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 where obj
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 the instanceof
conditional in your code ensures that obj
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...
Upvotes: 1
Reputation: 40461
instanceof
returns false if the argument is null
. So you don't need another check.
Upvotes: 12
Reputation: 10839
I've added comments inline below...
According to this, instanceof
returns false
, for a null
instance.
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");
}
}
Upvotes: 4