How to convert hardcoded enum to different language?

匆匆过客 提交于 2019-12-11 20:19:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!