使用PMD,如果您想忽略特定的警告,可以使用// NOPMD来忽略该行。
FindBugs也有类似的东西吗?
使用PMD,如果您想忽略特定的警告,可以使用// NOPMD来忽略该行。
FindBugs也有类似的东西吗?
当前回答
正如其他人提到的,您可以使用@SuppressFBWarnings Annotation。 如果不希望或不能向代码中添加另一个依赖项,则可以自己将Annotation添加到代码中,Findbugs并不关心Annotation位于哪个包中。
@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
/**
* The set of FindBugs warnings that are to be suppressed in
* annotated element. The value can be a bug category, kind or pattern.
*
*/
String[] value() default {};
/**
* Optional documentation of the reason why the warning is suppressed
*/
String justification() default "";
}
来源:https://sourceforge.net/p/findbugs/feature-requests/298/ # 5 e88
其他回答
FindBugs最初的方法涉及XML配置文件,也就是过滤器。这确实不如PMD解决方案方便,但是FindBugs处理字节码,而不是源代码,因此注释显然不是一个选项。例子:
<Match>
<Class name="com.mycompany.Foo" />
<Method name="bar" />
<Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>
但是,为了解决这个问题,FindBugs后来引入了另一种基于注释的解决方案(参见SuppressFBWarnings),您可以在类或方法级别使用它(在我看来比XML更方便)。例子(也许不是最好的,但这只是一个例子):
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value="HE_EQUALS_USE_HASHCODE",
justification="I know what I'm doing")
注意,由于与Java的SuppressWarnings名称冲突,FindBugs 3.0.0已经弃用了SuppressWarnings,取而代之的是@SuppressFBWarnings。
虽然这里的其他答案是有效的,但它们并不是解决这个问题的完整方法。
本着完整的精神:
你需要在你的pom文件中有findbugs注释-它们只是在编译时,所以你可以使用提供的作用域:
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>findbugs-annotations</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
这允许使用@ suppressbwarnings,还有另一个依赖项提供@SuppressWarnings。然而,上面的情况更清楚。
然后在你的方法上面添加注释:
E.g.
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
justification = "Scanning generated code of try-with-resources")
@Override
public String get() {
try (InputStream resourceStream = owningType.getClassLoader().getResourceAsStream(resourcePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceStream, UTF_8))) { ... }
这包括bug的名称和禁用扫描的原因。
最后,您需要重新运行findbugs以清除错误。
我把这个留在这里:https://stackoverflow.com/a/14509697/1356953
请注意,这适用于java.lang. suppresswarningso不需要使用单独的注释。
字段上的@SuppressWarnings仅抑制findbugs警告 为该字段声明报告,而不是与之关联的每个警告 该字段。 例如,这将抑制“字段只设置为null” 警告: @SuppressWarnings("UWF_NULL_FIELD") String s = null;我认为最好的 您所能做的就是将带有警告的代码隔离到最小 方法可以,然后压制整个方法上的警告。
正如其他人提到的,您可以使用@SuppressFBWarnings Annotation。 如果不希望或不能向代码中添加另一个依赖项,则可以自己将Annotation添加到代码中,Findbugs并不关心Annotation位于哪个包中。
@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
/**
* The set of FindBugs warnings that are to be suppressed in
* annotated element. The value can be a bug category, kind or pattern.
*
*/
String[] value() default {};
/**
* Optional documentation of the reason why the warning is suppressed
*/
String justification() default "";
}
来源:https://sourceforge.net/p/findbugs/feature-requests/298/ # 5 e88
在撰写本文时(2018年5月),FindBugs似乎已经被SpotBugs所取代。使用SuppressFBWarnings注释需要使用Java 8或更高版本编译代码,并在spotbugs-annotations.jar上引入编译时依赖项。
使用筛选器文件来筛选SpotBugs规则就没有这样的问题。文档在这里。