Is there a Sonar, Findbugs, or PMD rule that detects this possible NPE that CodePro detects?

790 Views Asked by At

Let's say I have a block of code like this:

Map<String, Object> mappy = 
    (Map<String, Object>)pExtraParameters.get(ServiceClientConstants.EXTRA_PARAMETERS);

if (pSSResponseBean!=null) {
    mappy.put(AddressResearchContext.CSI_RESPONSE_BEAN, (AddressNotFoundResponseBean)pSSResponseBean); // this line may  throw null pointer
}

Is there a Sonar, Findbugs, or PMD rule that will flag "mappy" as potentially null? Apparently CodePro flags this, and I need to provide something similar, if possible.

1

There are 1 best solutions below

4
On

The problem is that FindBugs treats unannotated items as if they were annotated with @Nullable which causes it to ignore nullness checks against them. You can create an empty java.util package annotated with a custom @ReturnValuesAreCheckForNullByDefault annotation (modify @ReturnValuesAreNonnullByDefault), but it will apply to every method in every class in that package.

@ReturnValuesAreCheckForNullByDefault
package java.util;

import edu.umd.cs.findbugs.annotations.ReturnValuesAreCheckForNullByDefault;

Another option is to create Map facade that has uses the @CheckForNull annotation.

public class AnnotatedMap<K, E> implements Map<K, E>
{
    private final Map<K, E> wrapped;

    @CheckForNull
    public E get(K key) {
        return wrapped.get(key);
    }
    ...
}

Update: See my previous answer to a similar question for complete details on implementing this advice.