6

I have an enum where values are presented in utf8 format. Because of this i have some encoding problems in my jsp view. Is there a way to get values from my messages.properties file. What if i have following lines in my properties file:

shop.first=Первый
shop.second=Второй
shop.third=Третий

How can i inject them in enum?

public enum ShopType {    
    FIRST("Первый"), SECOND("Второй"), THIRD("Третий");

    private String label;

    ShopType(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
user3127896
  • 6,323
  • 15
  • 39
  • 65

1 Answers1

6

I often have similar use cases, which I handle by putting the keys (not the localized values) as enum properties. Using a ResourceBundle (or a MessageSource when using Spring), I can resolve any such localized string whenever needed. This approach has two advantages:

  1. All localized strings can be stored into one single .properties file, which eliminates all encoding concerns in Java classes;
  2. It makes the code fully localizable (in fact, it will be one .properties file per locale).

This way, your enum will look like:

public enum ShopType {    
    FIRST("shop.first"), SECOND("shop.second"), THIRD("shop.third");

    private final String key;

    private ShopType(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }
}

(I removed the setter since an enum property should always be read-only. Anyway, it's not necessary anymore.)

Your .properties file remains the same.

Now comes the time to get a localized shop name...

ResourceBundle rb = ResourceBundle.getBundle("shops");
String first = rb.getString(ShopType.FIRST.getKey()); // Первый

Hope this will help...

Jeff

Jeff Morin
  • 1,010
  • 1
  • 13
  • 25
  • 2
    Be careful with this approach. `java.util.ResourceBundle#getBundle(java.lang.String)` doesn't support `UTF-8` encoding, it is assumed to use the `ISO 8859-1` character encoding. If your localisation files contains such characters, you need to use `java.util.Properties#load(java.io.Reader)` – GokcenG Oct 14 '17 at 13:10