开发者

Is there some way to assume @Nullable as default? (using FindBugs or any other free tool)

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?


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 don'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).


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.


What you're looking for is @ParametersAreNullableByDefault (http://code.google.com/p/jsr-305/source/browse/trunk/ri/src/main/java/javax/annotation/ParametersAreNullableByDefault.java) but I would urge you to use @ParametersAreNonnullByDefault instead. It would also have detected your buggy code. Preferably, you put them in your package-info.java file as an annotation on the package.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜