如何为具有特定注释的字段设置FindBugs过滤器?

Mar*_*tin 15 java eclipse findbugs

我有一个由FindBugs报告的错误,但我知道更好:)请参阅以下示例:

public class MyClass extends BaseClass {

    @CustomInjection
    private Object someField;

    public MyClass() {
        super();
        someField.someMethod(); // Bug is here because FindsBugs thinks this is always null
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的BaseClass构造函数中,我使用正确的对象注入带有@CustomInjection批注的所有字段,因此我的注释字段在我的情况下不为空.

我不想用'suppresswarnings'来抑制警告,因为这会使代码混乱很多.我宁愿做像FindBugs这样一个过滤器解释在这里,但我无法弄清楚如何筛选具有一定的界面注释字段错误.我也不想过滤所有空错误警告.我认为应该是这样的:

<Match>
  <Bug code="UR">  
  <Field annotation="CustomInjection">
</Match>
Run Code Online (Sandbox Code Playgroud)

Mar*_*tin 5

我找到了解决此问题的解决方法.似乎在FindBugs中对基于注释的注入的检测进行了硬编码,请参阅以下源代码:

public static boolean isInjectionAttribute(@DottedClassName String annotationClass) {
    if (annotationClass.startsWith("javax.annotation.")
            || annotationClass.startsWith("javax.ejb")
            || annotationClass.equals("org.apache.tapestry5.annotations.Persist")
            || annotationClass.equals("org.jboss.seam.annotations.In")
            || annotationClass.startsWith("javax.persistence")
            || annotationClass.endsWith("SpringBean")
            || annotationClass.equals("com.google.inject.Inject")
            || annotationClass.startsWith("com.google.") && annotationClass.endsWith(".Bind")
            && annotationClass.hashCode() == -243168318
            || annotationClass.startsWith("org.nuxeo.common.xmap.annotation")
            || annotationClass.startsWith("com.google.gwt.uibinder.client")
            || annotationClass.startsWith("org.springframework.beans.factory.annotation")
            || annotationClass.equals("javax.ws.rs.core.Context")) {
        return true;
    }
    int lastDot = annotationClass.lastIndexOf('.');
    String lastPart = annotationClass.substring(lastDot + 1);
    if (lastPart.startsWith("Inject")) {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

因此注释@EJB不会显示为UR错误,但我的注释@CustomInjection将始终是UR错误.

但是在函数的末尾有一个以"Inject"开头的所有注释名称的转义,所以如果我重命名@CustomInjection@InjectCustomUR错误就会消失.因此,要避免此问题,只需将注释重命名为@InjectSomething.