Is there any way to consider @Nullable as standard? (using FindBugs or any other free tool)

Consider this code

public void m1(String text) { if(text == null) text = "<empty>"; System.out.println(text.toLowerCase()); } 

And this is a mistake:

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

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

 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 error will be missed !!!

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

+4
source share
3 answers

According to Javadoc :

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

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

But according to chapter 10 of the FindBugs manual :

This is the same as DefaultAnnotation, except that it applies only to method parameters.

While theoretically either

 @DefaultAnnotationForParameters(value = Nullable.class) 

or

 @DefaultAnnotationForParameters({Nullable.class}) 

should work, both not .

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

+2
source

You can write your own detector in FindBugs, which searches for any use of parameters that do not have a zero mark. It would be relatively simple to do.

0
source

What you are 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 highly recommend you use @ParametersAreNonnullByDefault. He would also detect your buggy code. Preferably you put them in the package-info.java file as a package annotation.

0
source

Source: https://habr.com/ru/post/1309151/


All Articles