2013-01-11 41 views
8

我想要創建自定義註釋來抑制各個FindBugs警告,以便通過代碼完成來更容易地使用它們。例如,這個忽略不設置所有@Nonnull字段的構造函數。自定義註釋來抑制特定的FindBugs警告

@TypeQualifierDefault(ElementType.CONSTRUCTOR) 
@SuppressFBWarnings("NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") 
@Retention(RetentionPolicy.CLASS) 
public @interface SuppressNonnullFieldNotInitializedWarning 
{ } 

但是,我仍然看到使用註釋時的警告。

public class User { 
    @Nonnull 
    private String name; 

    @SuppressNonnullFieldNotInitializedWarning 
    public User() { 
     // "Nonnull field name is not initialized by new User()" 
    } 
} 

我已經嘗試了不同的保留策略和元素類型,將註釋的構造函數和類,甚至@TypeQualifierNickname

這種模式適用於將@Nonnull應用於類中的所有字段。

@Nonnull 
@TypeQualifierDefault(ElementType.FIELD) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface FieldsAreNonnullByDefault 
{ } 

FindBugs的正確顯示該分配nullname代碼警告。

@FieldsAreNonnullByDefault 
public class User { 
    private String name; 

    public UserModel() { 
     name = null; 
     // "Store of null value into field User.name annotated Nonnull" 
    } 
} 

我相信問題是@SuppressFBWarnings沒有打上@TypeQualifier@Nonnull是,這樣@TypeQualifierDefault@TypeQualifierNickname並不適用於它。但是必須有一些其他機制來使用另一個註釋來應用一個註釋。

+1

@克里斯:這個答案描述瞭如何使用findbugs SuppressWarning註釋。這個問題是如何創建一個新的註釋來抑制特定的findbugs警告。 – TimK

+0

@Chris您已在此處發佈第二個鏈接:http://stackoverflow.com/questions/14285422/custom-annotation-to-suppress-a-specific-findbugs-warning#comment19837178_14285422 – steffen

回答

1

(並非專門回答問題),但如果您只是想用@SuppressFBWarnings使代碼完成更好地工作,則可以爲每個警告代碼定義一個static final String,然後使用註釋中的代碼。例如

public final class FBWarningCodes { 
    private FBWarningCodes() { } 

    public static final String NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR = "NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR"; 
} 

然後:

import static com.tmobile.tmo.cms.service.content.FBWarningCodes.*; 

@SuppressFBWarnings(NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR) 

(但無可否認Eclipse不希望做代碼完成,除非你在註釋中註明value=

+0

這是我目前的解決方案,儘管我縮短了常數名稱。 –

+3

下面是Eclipse用戶的模板:fb - '@ $ {suppress:newType(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)}($ {warning:newType(com.tmobile.tmo.cms.service.content。 FBWarningCodes)}。$ {cursor})'鍵入'fb',按Ctrl-Space兩次,然後選擇要禁止的警告。 –