如何将硬编码的枚举转换为不同的语言? [英] How to convert hardcoded enum to different language?

查看:187
本文介绍了如何将硬编码的枚举转换为不同的语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自动生成一个我使用的webservice的枚举,所以我不能修改这个枚举类,因为进一步的更新会覆盖它。



我想提供枚举的翻译:

  //我不能修改这个类
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆