Custom annotation to suppress a specific FindBugs warning

I want to create custom annotations to suppress individual FindBugs warnings, to make them easier to use with code completion. For example, it ignores constructors that do not set all @Nonnull fields.

 @TypeQualifierDefault(ElementType.CONSTRUCTOR) @SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") @Retention(RetentionPolicy.CLASS) public @interface SuppressNonnullFieldNotInitializedWarning { } 

However, I still see a warning when using annotations.

 public class User { @Nonnull private String name; @SuppressNonnullFieldNotInitializedWarning public User() { // "Nonnull field name is not initialized by new User()" } } 

I tried different storage policies and item types, putting annotation in the constructor and class, and even @TypeQualifierNickname .

The same template works to apply @Nonnull to all fields of a class.

 @Nonnull @TypeQualifierDefault(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface FieldsAreNonnullByDefault { } 

FindBugs correctly displays a warning for code that assigns a null name .

 @FieldsAreNonnullByDefault public class User { private String name; public UserModel() { name = null; // "Store of null value into field User.name annotated Nonnull" } } 

I believe the problem is that @SuppressFBWarnings not tagged @TypeQualifier , but @Nonnull is, and thus @TypeQualifierDefault and @TypeQualifierNickname do not apply to it. But there must be some other mechanism for applying one annotation using another.

+8
java annotations findbugs
source share
1 answer

(Not specifically answering the question), but if you just want to improve the code using @SuppressFBWarnings , you can define a static final String for each of the warning codes, and then use the ones indicated in the annotation. eg.

 public final class FBWarningCodes { private FBWarningCodes() { } public static final String NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR"; } 

Then:

 import static com.tmobile.tmo.cms.service.content.FBWarningCodes.*; @SuppressFBWarnings(NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR) 

(although, admittedly, Eclipse does not want to execute code completion unless you specify value= in the annotation)

+1
source share

All Articles