views:

121

answers:

2

Consider such code

public void m1(String text) {
    if(text == null)
        text = "<empty>";

    System.out.println(text.toLowerCase());
}

And this is a buggy version:

public void m1(String text) {
    System.out.println(text.toLowerCase());
}

If null value passed, the NullPointerException may be thrown. I would like the static-analysis tool (e.g. FindBugs) to report this issue. Unsuccessfully the FindBugs (at least by default) requires me to specify @Nullable annotation explicitly.

public void m1(@Nullable String text) {
    System.out.println(text.toLowerCase()); // FindBugs: text must be nonnull but is marked as nullable
}

The problem is that if I forget to annotate it, the bug will be missed!!!

How can I make the FindBugs (or any other free tool) to assume @Nullable by default?

+2  A: 

According to Javadoc:

@DefaultAnnotationForParameters indicates that all members of the class or package should be annotated with the default value of the supplied annotation class.

(BTW Javadocs for @DefaultAnnotation, @DefaultAnnotationForFields and @DefaultAnnotationForMethods contain exactly the same text).

But according to chapter 10 of FindBugs Manual:

This is same as the DefaultAnnotation except it only applys to method parameters.

While theroretically either

@DefaultAnnotationForParameters(value = Nullable.class)

or

@DefaultAnnotationForParameters({Nullable.class})

should work, both doesn't.

I don't know if FindBugs supports this but with JSR 305 you can also use @ParametersAreNullableByDefault annotation applied to a package, class or method. Unfortunately FindBugs 1.3.9 ignores @ParametersAreNonnullByDefault and similar annotations (used on packages or on types).

Jacek S
Does it work for your? If yes, what is your version (mine FindBug 1.3.9)?
alex2k8
Tried 1.3.7, 1.3.8, 1.3.9. I added annotations for class and for package (using package-info.java) - no luck...
alex2k8
perhaps CheckForNull.class will work better as the default annotation
TheDon
@alex2k8: I've updated the answer. @DefaultAnnotationForParameters works like it's supposed to with some other nullness annotations, but I had no luck with Nullable either.
Jacek S
@Jacek, thank you for your research.
alex2k8
A: 

You can write your own detector in FindBugs that looks for any use of parameters that are not null checked. Would be relatively simple to do.

MeBigFatGuy