[英]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.