2009-12-02 94 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

相關問題