避免重复文字声纳错误

时间:2016-07-06 14:29:48

标签: java sonarqube

我使用SonarQube来验证和检查我的Java代码,并且我在Enum类类型中遇到了避免重复文字的问题,这是一个例子:

ProgramFiles/jre_version
声纳告诉我声明弦乐'产品A'和'产品B'作为常量字段,但您不能在Enum类型类中声明变量。

2 个答案:

答案 0 :(得分:2)

您可以在枚举之外声明常量:

private static final String TYPE_A_NAME = "Type A";

public enum Type {

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

    private String value;

    Type(String value) {

    }
}

答案 1 :(得分:0)

创建前缀(私有静态最终Sting PREFIX = Product.class.getSimpleName()+“。”

和A(“A”)等......

如果返回一个字符串,则可以使用MessageFormatter将属性文件中的字符串国际化

Product.A =产品A等......

,构造函数是私有的

你可以像

那样做一个吸气鬼

`

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

public class 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);
}

}

`