2016-07-06 64 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); 
} 

}

`