自定义注释以禁止特定的FindBugs警告

Dav*_*ess 9 java annotations findbugs

我想创建自定义注释来抑制单个FindBugs警告,以便通过代码完成更容易地使用它们.例如,这个忽略不设置所有@Nonnull字段的构造函数.

@TypeQualifierDefault(ElementType.CONSTRUCTOR)
@SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
@Retention(RetentionPolicy.CLASS)
public @interface SuppressNonnullFieldNotInitializedWarning
{ }
Run Code Online (Sandbox Code Playgroud)

但是,在使用注释时我仍然会看到警告.

public class User {
    @Nonnull
    private String name;

    @SuppressNonnullFieldNotInitializedWarning
    public User() {
        // "Nonnull field name is not initialized by new User()"
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的保留策略和元素类型,将注释放在构造函数和类上,甚至@TypeQualifierNickname.

这种模式适用@Nonnull于类中的所有字段.

@Nonnull
@TypeQualifierDefault(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsAreNonnullByDefault
{ }
Run Code Online (Sandbox Code Playgroud)

FindBugs正确显示分配null给代码的警告name.

@FieldsAreNonnullByDefault
public class User {
    private String name;

    public UserModel() {
        name = null;
        // "Store of null value into field User.name annotated Nonnull"
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信这个问题是@SuppressFBWarnings没有标记@TypeQualifier@Nonnull为,并因此@TypeQualifierDefault@TypeQualifierNickname并不适用于它.但是必须有一些其他机制来使用另一个注释来应用一个注释.

pau*_*lcm 1

(不是专门回答这个问题),但是如果您只是想让代码完成更好地工作@SuppressFBWarnings,您可以static final String为每个警告代码定义一个,然后在注释中使用它们。例如

public final class FBWarningCodes {
    private FBWarningCodes() { }

    public static final String NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR";
}
Run Code Online (Sandbox Code Playgroud)

然后:

import static com.tmobile.tmo.cms.service.content.FBWarningCodes.*;

@SuppressFBWarnings(NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR)
Run Code Online (Sandbox Code Playgroud)

value=(尽管不可否认,除非您在注释中指定,否则 Eclipse 不想执行代码完成)

  • 以下是 Eclipse 用户的模板:fb - `@${suppress:newType(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)}(${warning:newType(com.tmobile.tmo.cms.service.content.FBWarningCodes) )}.${cursor})` 输入 `fb`,按 Ctrl-空格键两次,然后选择要抑制的警告。 (3认同)