Reputation: 693
I'm using SonarQube to verify and inspect my Java code, and i've encountered an issue with Avoid Duplicate Literals in an Enum class type, here is an exemple :
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;
}
}
Sonar is telling me to declare the Strings 'Product A' and 'Product B' as a constant field, but you can't declare variables in Enum type class.
Upvotes: 5
Views: 12041
Reputation: 2993
You can declare the constant outside of the enum:
private static final String TYPE_A_NAME = "Type A";
public enum Type {
TYPEA(TYPE_A_NAME), TYPEB("B");
private String value;
Type(String value) {
}
}
Upvotes: 2
Reputation: 88
Create Prefix (private static final Sting PREFIX = Product.class.getSimpleName()+ "."
and A("A"), etc...
you return a string, you can use a MessageFormatter to internationalize your string in a properties file
Product.A=Product A, etc...
and the constructor is private
you can make a getter like
`
public static String getI18NString(String key){
return Internationalizer.getI18String(PREFIX + key);
}
public class Internationalizer { /** The logger of this class. */ 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);
}
}
`
Upvotes: 0