如何将硬编码的枚举转换为不同的语言? [英] How to convert hardcoded enum to different language?
问题描述
我想提供枚举的翻译:
//我不能修改这个类
public enum Time {
PAST 过去),现在(现在),未来(未来);
private final String value;
}
//我的代码
时间= getTimeFromWebservice();
字符串翻译;
switch(time.value()){
case:过去:translation =Vergangenheit;打破;
case:Present:translation =Gegenwart;打破;
case:Future:translation =Zukunft;打破;
}
我如何改善这一点?
您不能在运行时动态扩展/修改枚举。他们被视为常数。
通常如果你想做国际化,所有的翻译都是从一个 ResourceBundle
加载的。您可以使用枚举文字作为关键:
String translation = bundle.getString(time.name());
或者你可能想要键入前缀:
String translation = bundle.getString(myprefix。+ time.name());
//或使用完全限定名:
字符串翻译= bundle.getString(time.getClass()。getCanonicalName()+。+ time.name());
请参阅 http://docs.oracle.com/javase/tutorial/i18n/resbundle/index.html 详细信息。
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?
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.
这篇关于如何将硬编码的枚举转换为不同的语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!