Why findbugs provide redundant nullcheck for one method but not others

I use @Nonnull and @Nullable method annotations to give other programmers (and me!) A hint about what the method can return. Finally, I decided to actually run Findbugs in the class (IntelliJ - FindBugs-IDEA v1.0.1), and I do not understand the behavior that I see. The documentation also did not help.

Let's say I have the following code example:

import javax.annotation.Nonnull; public class Main { public static void main(String[] args) { } @Nonnull public static String myFunc(){ return new String("foo"); } @Nonnull public static String myFunc2(){ return "foo"; } } 

Findbugs flags myFunc () returns the statement as having a "redundant nullcheck value that is not known to be null", but is happy with myFunc2 ().

Are findbugs expected to see this differently? (A link to the documentation would be appreciated) Am I completely misunderstanding the use of @Nonnull in methods?

[edit]

After some research, I decided that the org.jetbrains @Contract annotation (with a contract change to bugs) would better satisfy my needs. Thanks Guillaume F. for your help!

+8
java findbugs
source share
1 answer

You need to understand what redundant Null-Check means. When Findbugs gives you this warning, it means that you have done Null-Check twice, but not the second time. Which matches your example.

In the first code, new String("foo") performs an implicit zero check because new String(null) will throw an exception. Thus, this new String object is implicitly checked non-zero. Then you do another @Nonnull check, leaving the method. Findbugs sees this and warns.

Your second code doesnโ€™t have such a control, since you are returning the raw string and performing the @Nonnull check only once. Everything is good.


You might want to use edu.umd.cs.findbugs.annotations.NonNull instead. This one will just tell Findbugs that you want to get a null result without having a real check.

If you are using Maven:

  <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> <version>${findbugs-annotations.version}</version> <scope>provided</scope> </dependency> 

https://blogs.oracle.com/java-platform-group/entry/java_8_s_new_type

What @NotNull Java annotation should I use?

+1
source share

All Articles