我想要創建自定義註釋來抑制各個FindBugs警告,以便通過代碼完成來更容易地使用它們。例如,這個忽略不設置所有@Nonnull
字段的構造函數。自定義註釋來抑制特定的FindBugs警告
@TypeQualifierDefault(ElementType.CONSTRUCTOR)
@SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
@Retention(RetentionPolicy.CLASS)
public @interface SuppressNonnullFieldNotInitializedWarning
{ }
但是,我仍然看到使用註釋時的警告。
public class User {
@Nonnull
private String name;
@SuppressNonnullFieldNotInitializedWarning
public User() {
// "Nonnull field name is not initialized by new User()"
}
}
我已經嘗試了不同的保留策略和元素類型,將註釋的構造函數和類,甚至@TypeQualifierNickname
。
這種模式適用於將@Nonnull
應用於類中的所有字段。
@Nonnull
@TypeQualifierDefault(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsAreNonnullByDefault
{ }
FindBugs的正確顯示該分配null
到name
代碼警告。
@FieldsAreNonnullByDefault
public class User {
private String name;
public UserModel() {
name = null;
// "Store of null value into field User.name annotated Nonnull"
}
}
我相信問題是@SuppressFBWarnings
沒有打上@TypeQualifier
而@Nonnull
是,這樣@TypeQualifierDefault
和@TypeQualifierNickname
並不適用於它。但是必須有一些其他機制來使用另一個註釋來應用一個註釋。
@克里斯:這個答案描述瞭如何使用findbugs SuppressWarning註釋。這個問題是如何創建一個新的註釋來抑制特定的findbugs警告。 – TimK
@Chris您已在此處發佈第二個鏈接:http://stackoverflow.com/questions/14285422/custom-annotation-to-suppress-a-specific-findbugs-warning#comment19837178_14285422 – steffen