Localizing enum values in resource bundle

后端 未结 5 727
借酒劲吻你
借酒劲吻你 2020-11-27 05:00

I have a problem with i18n enums in my JSF application. When I started, I had enums with the text defined inside. But now, I have keys tied to message bundles in the enum.

5条回答
  •  执笔经年
    2020-11-27 05:18

    Well, enum is just another class. There is nothing stopping you from adding parsing and to-string conversion methods that will parse and output locale-sensitive messages.

    Maybe it violates Single Responsible Principle (does it?), but I believe making enum responsible for parsing and returning locale-aware values is the right thing to do.

    Just add two methods like this:

    public String toString(FacesContext context) {
       // need to modify the method   
       FacesUtil.getMessageValue(context, name);
    }
    
    public OrderStatus parse(FacesContext context, String theName) {
      for (OrderStatus value : values()) {
        if (value.toString(context).equals(theName) {
          return value;
        }
      }
      // think of something better
      return null;
    }
    

    I hope I got the code right, as I am not checking it with IDE now... Is this what you were looking for?

提交回复
热议问题