2009-12-02 97 views

回答

250

FindBugs的初始方法涉及到XML配置文件,即filters。这实际上比PMD解决方案不太方便,但FindBugs可以在字节码上工作,而不是在源代码上工作,所以评论显然不是一种选择。例如:

<Match> 
    <Class name="com.mycompany.Foo" /> 
    <Method name="bar" /> 
    <Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" /> 
</Match> 

但是,要解决这个问题,FindBugs的后来推出了基于annotations另一种解决方案(见SuppressFBWarnings),你可以在类或方法级别(比XML更方便在我看来)使用。示例(也许不是最好的之一,但,好吧,这只是一个例子):

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value="HE_EQUALS_USE_HASHCODE", 
    justification="I know what I'm doing") 

注意,因为FindBugs的3.0.0 SuppressWarnings一直赞成@SuppressFBWarnings反对,因为名称冲突与Java的SuppressWarnings的。

+79

+1的评论:“我知道我在做什么” – dhiller 2009-12-02 05:44:20

+4

奖金问题:我如何找到一个给定报“臭虫”(使用声纳)适当的价值? – PlanBForOpenOffice 2011-08-04 16:35:52

+27

当然,使用注解方法的问题在于,您的代码相当不必要地导入(以及随后的依赖项)Findbugs库:( – 2012-02-03 10:25:26

13

下面是一个XML过滤器的更完整的例子(上面的例子本身是行不通的,因为它只是显示一个片段,并缺少<FindBugsFilter>开始和结束标记):

<FindBugsFilter> 
    <Match> 
     <Class name="com.mycompany.foo" /> 
     <Method name="bar" /> 
     <Bug pattern="NP_BOOLEAN_RETURN_NULL" /> 
    </Match> 
</FindBugsFilter> 

如果你是使用Eclipse FindBugs插件,使用Window-> Preferences-> Java-> FindBugs-> Filter files-> Exclude filter files-> Add来浏览到您的XML过滤器文件。

-5

我要离开这个位置:https://stackoverflow.com/a/14509697/1356953

请注意,这一点也适用java.lang.SuppressWarnings因此无需使用单独的注解。在现场

@SuppressWarnings仅抑制 报道了那场声明,不与 该领域相关的每一个警告FindBugs的警告。

例如,这抑制了 “字段只有永远设置为空” 警告:

@SuppressWarnings( “UWF_NULL_FIELD”)的String = NULL;我认为你可以做的最好的 是将带有警告的代码隔离到最小的方法 ,然后在整个方法上禁止警告。

+5

'java.lang.SuppressWarnings'不能工作。它具有源保留,所以对findbugs不可见。 – 2016-03-22 09:32:26

5

更新摇篮

dependencies { 
    compile group: 'findbugs', name: 'findbugs', version: '1.0.0' 
} 

找到FindBugs的报告

文件:///用户/ your_user/IdeaProjects /项目名称/编译/报告/ FindBugs的/主。HTML

查找特定消息

find bugs

导入正确的版本注释的

import edu.umd.cs.findbugs.annotations.SuppressWarnings; 

添加注释正上方有问题的代码

@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX") 

这里看到更多的信息:findbugs Spring Annotation

+1

你可以使用'compile'net.sourceforge.findbugs:annotations:1.3.2''语法来代替它。 – 2016-10-11 13:17:40

+1

+1,但请更新您的答案:gradle'testCompile'c​​om.google.code.findbugs:annotations:3.0.0''和注释名称'@ SuppressFBWarnings' – 2017-05-26 18:02:39

10

正如其他人所说,你可以使用@SuppressFBWarnings注解。 如果您不想或不能添加其他依赖项到您的代码中,您可以自己将注释添加到您的代码中,Findbugs无需关心Annotation所在的Package。

@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/#5e88

相关问题