How to localize enum values in GWT client code?

前端 未结 3 1487
孤街浪徒
孤街浪徒 2021-02-18 19:01

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\"), THIR         


        
相关标签:
3条回答
  • 2021-02-18 19:38

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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-18 19:46

    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.

    0 讨论(0)
提交回复
热议问题