[英]Custom annotation to suppress a specific FindBugs warning
I want to create custom annotations to suppress individual FindBugs warnings to make it easier to use them via code-completion. 我想创建自定义注释来抑制单个FindBugs警告,以便通过代码完成更容易地使用它们。 For example, this one ignores constructors that don't set all @Nonnull
fields. 例如,这个忽略了没有设置所有@Nonnull
字段的构造函数。
@TypeQualifierDefault(ElementType.CONSTRUCTOR)
@SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
@Retention(RetentionPolicy.CLASS)
public @interface SuppressNonnullFieldNotInitializedWarning
{ }
However, I still see the warning when using the annotation. 但是,在使用注释时我仍然会看到警告。
public class User {
@Nonnull
private String name;
@SuppressNonnullFieldNotInitializedWarning
public User() {
// "Nonnull field name is not initialized by new User()"
}
}
I've tried different retention policies and element types, putting the annotation on the constructor and the class, and even @TypeQualifierNickname
. 我尝试了不同的保留策略和元素类型,将注释放在构造函数和类上,甚至是@TypeQualifierNickname
。
This same pattern works to apply @Nonnull
to all fields in a class. 这种模式适用于将@Nonnull
应用于@Nonnull
中的所有字段。
@Nonnull
@TypeQualifierDefault(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsAreNonnullByDefault
{ }
FindBugs correctly displays a warning for code that assigns null
to name
. FindBugs正确显示为name
指定null
代码的警告。
@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
is not marked with @TypeQualifier
while @Nonnull
is, and thus @TypeQualifierDefault
and @TypeQualifierNickname
don't apply to it. 我认为问题是@SuppressFBWarnings
没有用@TypeQualifier
标记而@Nonnull
是,因此@TypeQualifierDefault
和@TypeQualifierNickname
不适用于它。 But there must be some other mechanism to apply one annotation using another. 但是必须有一些其他机制来使用另一个注释来应用一个注释。
(Not specifically answering the question), but if you just want to make code-completion work better with @SuppressFBWarnings
, you could define a static final String
for each of the warning codes and then use those in the annotation. (不是专门回答这个问题),但是如果你只是想用@SuppressFBWarnings
更好地完成代码完成工作,你可以为每个警告代码定义一个static final String
,然后在注释中使用它们。 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)
(though admittedly Eclipse doesn't want to do code-completion unless you specify value=
in the annotation) (虽然不可否认Eclipse除了在注释中指定value=
不想进行代码完成)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.