Again something that has been discussed before and where I wanted to share "my" solution and ask for enhancements, other approaches or best practices.
I have several enums where I need internationalization (I need the enum values translated into some languages in order to display them in a jsf page). Examle enum:
public enum TransferStatus {
NOT_TRANSFERRED,
TRANSFERRED
}
Translation would be for example Not yet transferred
/ Transferred, all good
The translation should be stored in a MessageBundle (properties files). I was searching for an easy, generic solution (best would be without the need of writing extra code in all the enums) that does not need much on the jsf side. Just to mention it, of course it it possible that two different enums shae the same enum value (e.g. values like COMPLETED
that have a different meaning in different enums).
The solution I came up with:
(1) Store translations in the properties file like this:
TransferStatus.NOT_TRANSFERRED = Not yet transferred
TransferStatus.TRANSFERRED = Transferred, all good
(2) Make a helper class that takes an enum and generates the lookup key:
public class EnumTranslator {
public static String getMessageKey(Enum<?> e) {
return e.getClass().getSimpleName() + '.' + e.name();
}
}
(3) Add this code to every enum:
public String getKey() {
return EnumTranslator.getMessageKey(this);
}
(4) Now, I can access the translated values of my enums like this:
<h:outputText value="#{enum[order.transferStatus.key]}" />
Which is okay, but what I just don't like is adding the same getKey()
method to every enum. There should be something better that that! Now it's your turn, SO :-)