问题
I have an enum that is autogenerated of a webservice I use, thus I cannot modify this enum class as further update would override it.
I would like to provide translation for the enum:
//I cannot modify this class
public enum Time {
PAST("Past"), PRESENT("Present"), FUTURE("Future");
private final String value;
}
//my code
Time time = getTimeFromWebservice();
String translation;
switch(time.value()) {
case: "Past": translation = "Vergangenheit"; break;
case: "Present": translation = "Gegenwart"; break;
case: "Future": translation = "Zukunft"; break;
}
How could I improve this?
回答1:
You cannot dynamically extend/modify enums at runtime. They are treated like constants.
Usually if you want to do internationlization, all translations are loaded from a ResourceBundle
. You can use the enum literal as key:
String translation = bundle.getString(time.name());
Or maybe you want to prefix the key:
String translation = bundle.getString("myprefix." + time.name());
// or use full qualified name:
String translation = bundle.getString(time.getClass().getCanonicalName() + "." + time.name());
See http://docs.oracle.com/javase/tutorial/i18n/resbundle/index.html for details.
来源:https://stackoverflow.com/questions/20287009/how-to-convert-hardcoded-enum-to-different-language