【问题标题】:How to convert hardcoded enum to different language?如何将硬编码的枚举转换为不同的语言?
【发布时间】:2013-11-29 13:32:49
【问题描述】:

我有一个由我使用的网络服务自动生成的枚举,因此我无法修改此枚举类,因为进一步更新会覆盖它。

我想为枚举提供翻译:

//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;
}

我该如何改进?

【问题讨论】:

  • 首先,我会打开枚举值本身而不是它们的字符串值:switch (time) { case PAST: ... case PRESENT: ... }
  • 哦,是的,这样好多了!

标签: java enums internationalization


【解决方案1】:

您不能在运行时动态扩展/修改枚举。它们被视为常量。

通常如果你想做国际化,所有的翻译都是从ResourceBundle加载的。您可以使用枚举文字作为键:

String translation = bundle.getString(time.name());

或者您可能想为键添加前缀:

String translation = bundle.getString("myprefix." + time.name());

// or use full qualified name:
String translation = bundle.getString(time.getClass().getCanonicalName() + "." + time.name());

详情请见http://docs.oracle.com/javase/tutorial/i18n/resbundle/index.html

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 2021-05-07
    • 2016-03-20
    • 2010-09-06
    相关资源
    最近更新 更多