2

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.

David Harkness
  • 35,992
  • 10
  • 112
  • 134
David M. Karr
  • 14,317
  • 20
  • 94
  • 199

1 Answers1

0

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.

Community
  • 1
  • 1
David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • I don't quite get the first technique. Are you simply saying to define a "java/util/package-info.java" with that annotation in my source tree? I wonder if that will conflict with an existing "package-info.java" for that package from the JDK? – David M. Karr Apr 18 '13 at 15:13
  • I'm also confused about your reference to a "custom" annotation. I'm guessing you're saying that we should define that annotation, basing it on the existing @ReturnValuesAreNonnullByDefault annotation, but I have no idea how that new annotation should be different from the existing one. – David M. Karr Apr 18 '13 at 16:45
  • Oh, I guess http://stackoverflow.com/questions/14194304/how-to-use-findbugs-nonnull-with-external-libraries is relevant to this. – David M. Karr Apr 18 '13 at 16:46
  • @DavidM.Karr - Yes, thanks for finding that link. I got interrupted while writing this answer. You understand correctly, except that it doesn't seem to interfere with an existing package info. In the JDK they only contain package comments AFAIK. The new annotation will differ by being annotated with `@CheckForNull` instead of `@Nonnull`. This will apply the former to all method return values in that package. – David Harkness Apr 18 '13 at 20:19