2016-07-06 60 views
1

我使用SonarQube覈實和檢查我的Java代碼,我遇到在一個枚舉類類型避免重複字面的問題,這裏是個例:避免重複字面聲納錯誤

public enum Products { 

    A ("Product A"), 
    C ("Product A"), 
    D ("Product B"), 
    P ("Product B"); 

    private String name = ""; 

    Products (String name){ 
    this.name = name; 
    } 

    public String toString(){ 
    return name; 
    } 
} 

聲納告訴我將字符串的產品A和產品B聲明爲一個常量字段,但不能在Enum類型類中聲明變量。

回答

1

您可以聲明枚舉的不斷外:

private static final String TYPE_A_NAME = "Type A"; 

public enum Type { 

    TYPEA(TYPE_A_NAME), TYPEB("B"); 

    private String value; 

    Type(String value) { 

    } 
} 
+0

謝謝您的回答:) – Sofiane

0

創建前綴(私有靜態最後斯汀PREFIX = Product.class.getSimpleName()+ 「」

和A( 「A」),等等

你返回一個字符串,你可以使用MessageFormatter國際化你的字符串在屬性文件

Product.A =產品A,等...

和構造函數是私有

你CA n請一個getter像

`

public static String getI18NString(String key){ return Internationalizer.getI18String(PREFIX + key); }

公共類Internationalizer { /**這個類的記錄。 */ private static final Log LOGGER = LogFactory.getLog(Internationalizer.class);

/** */ 
private static ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); 

/** 
* Get the internationalized String form properties files 
* 
* @param key 
* @return 
*/ 
public static String getI18String(final String key) { 
    String message = ""; 
    try { 
     message = resourceBundleMessageSource.getMessage(key, null, Locale.getDefault()); 
    } catch (NoSuchMessageException e) { 
     LOGGER.info("Key not internationalized : " + key); 
     message = key; 
    } 
    return message; 
} 

/** 
* Set the bundles for internationalization Injected by Spring 
* 
* @param bundles 
*/ 
public void setBundles(final List<String> bundles) { 
    String[] bundlesArrays = new String[bundles.size()]; 
    for (int i = 0; i < bundles.size(); i++) { 
     bundlesArrays[i] = bundles.get(i); 
    } 
    resourceBundleMessageSource.setBasenames(bundlesArrays); 
} 

}

`