Is there a standard annotation for a class that is NOT deprecated that sets non-zero default return values

Google is failing. This annotation used to be: ReturnValuesAreNonnullByDefault .

But this is now deprecated, and javadoc does not indicate which new annotation to use. @Nonnull for the whole class is not applicable for return values, because I just checked this and I did not receive a warning that the method returns null. I do not want to specifically comment on each return value, so is there a good option?

+5
source share
2 answers

You can use this answer to create your own simple @EverythingIsNonnullByDefault annotation to be applied at the package / class level to cover all cases, or this one that shows you how to create separate annotations to control the fields and return values ​​of a method. We decided to use all of them, but, as a rule, we use the β€œall” version at the package level.

If you're really in a hurry, copy-n-paste the legacy annotation and delete the legacy version.

 package com.sample; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.annotation.meta.TypeQualifierDefault; /** * This annotation can be applied to a package or class to indicate that the * classes' methods in that element all return nonnull values by default * unless there is * <ul> * <li>an explicit nullness annotation * <li>a default method annotation applied to a more tightly nested element. * </ul> */ @Documented @Nonnull @TypeQualifierDefault(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ReturnValuesAreNonnullByDefault { // feel free to name it MethodsAreNonnullByDefault; I find that confusing } 
+1
source

If you use the Checker Framework , you can use @DefaultQualifier . For example, you can write

 @DefaultQualifier(value=NonNull.class, locations=DefaultLocation.RETURNS) 

However, you do not need to do this because the Checker Framework Nullness Checker already uses this default value. (As you discovered, the best default is that each method returns null.)

The advantage of Nullness Checker is that it detects more null pointer errors than FindBugs.

Nullness Checker is compatible with FindBugs annotations, so you can try Nullness Checker without modifying existing FindBugs annotations in your code.

+1
source

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


All Articles