繁体   English   中英

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

[英]How to Set a FindBugs Filter for fields with a specific Annotation?

我有一个由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
    }
}

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

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

<Match>
  <Bug code="UR">  
  <Field annotation="CustomInjection">
</Match>

我找到了解决此问题的解决方法。 似乎在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;
}

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

但是在函数结束时,所有注释名称都以“Inject”开头,所以如果我将@CustomInjection重命名为@InjectCustom ,UR错误就会消失。 因此,要避免此问题,只需将注释重命名为@InjectSomething

如果您不能直接执行此操作,请编写一个检测注释的预处理器,并生成用于使其使用看起来对FindBugs有效的代码来初始化该字段。 将预处理器输出提供给FindBugs,而不是原始源代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM