Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to localize enum values in GWT client code?

Tags:

java

gwt

I am using an enumeration class in my GWT client's code to define a set of types.

public enum MyType {

    FIRST_TYPE("first"), SECOND_TYPE("second"), THIRD_TYPE("third");

    private String title;

    private MyType(String title) {
        this.title = title;
    }

    public String getTitle() {
        return this.title;
    }

}

How is it possible to localize the enum values to translate them into different languages? The title field is not that important and could be dropped if this helps to solve the problem.

I know the ResourceBundle approach from Java, but that is not working in GWT's client code.

like image 994
thommyslaw Avatar asked Sep 21 '10 05:09

thommyslaw


3 Answers

I managed to solve the problem by using GWT's ConstantsWithLookup interface. Here is the solution:

MyType.java

public enum MyType {

    FIRST_TYPE, SECOND_TYPE, THIRD_TYPE;

    private final MyConstantsWithLookup constants = GWT.create(MyConstantsWithLookup.class)

    public String getTitle() {
        return this.constants.getString(this.name());
    }
}

MyConstantsWithLookup.java

public interface MyConstantsWithLookup extends ConstantsWithLookup {

    String FIRST_TYPE();

    String SECOND_TYPE();

    String THIRD_TYPE();
}

MyConstantsWithLookup.properties

FIRST_TYPE = first
SECOND_TYPE = second
THIRD_TYPE = third
like image 104
thommyslaw Avatar answered Oct 05 '22 20:10

thommyslaw


I would like to add to @thommyslaw answer that in some cases you may need to pass Enums thru the wire. I mean make them serializable. In such cases putting GWT.create() inside the Enum will not work. Here is where some kind of Singleton Glossary class will be handy, like:

public class LEGlossary {

private static LEGlossary instance=null;
private static final LocalizationEnum localConstants=GWT.create(LocalizationEnum.class);

private LEGlossary(){

}

public static LEGlossary instance(){
    if(instance==null){
        instance=new LEGlossary();
    }
    return instance;
}

public String localizedValue(Enum<?> value){
    return localConstants.getString(value.name());
}


}

Where LocalizationEnum in my case extends ConstantsWithLookup interface. In this way you isolate the localization code on the client and leave the Enum free to pass thru the wire.

like image 23
Daniel Ardison Avatar answered Oct 05 '22 20:10

Daniel Ardison


Maybe this will help you, since it seems to be the gwt way Internationalization

like image 41
InsertNickHere Avatar answered Oct 05 '22 21:10

InsertNickHere