|
Re: Localizing Enums [message #894432 is a reply to message #893019] |
Mon, 09 July 2012 08:42 |
Alexey Romanov Messages: 263 Registered: May 2010 |
Senior Member |
|
|
I ended up with a pretty simple solution:
package ru.focusmedia.rcplibs.rcputil;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.osgi.util.NLS;
public abstract class NLSEnum extends NLS {
private static Map<Class<?>, Map<Enum<?>, String>> classesToEnumMessages;
public static String getEnumText(Enum<?> enumValue, Class<?> nlsClass) {
return getEnumText(enumValue, nlsClass, enumValue.getDeclaringClass().getSimpleName());
}
public static String getEnumText(Enum<?> enumValue, Class<?> nlsClass, String prefix) {
Map<Enum<?>, String> enumMessages = classesToEnumMessages.get(nlsClass);
if (enumMessages == null) {
enumMessages = new HashMap<Enum<?>, String>();
classesToEnumMessages.put(nlsClass, enumMessages);
}
String storedResult = enumMessages.get(enumValue);
if (storedResult != null) {
return storedResult;
} else {
String result;
try {
String fieldName = prefix + "_"
+ enumValue.name();
Field field = nlsClass.getField(fieldName);
result = (String) field.get(null);
} catch (Exception e) {
result = (enumValue.name().charAt(0) + enumValue.name().substring(1).toLowerCase()).replace('_', ' ');
}
enumMessages.put(enumValue, result);
return result;
}
}
}
In extending class:
public class Msg extends NLSEnum {
public String getYesNoMsg(YesNo arg) {
return getEnumText(arg, Msg.class);
}
}
|
|
|
Powered by
FUDForum. Page generated in 0.03075 seconds