Best approach for multilingual Java Enum

I’m running into issues with an approach I am taking and am now wondering if I just started down the wrong path and should rethink my approach. Here is what I attempting.

I would like to use an Enum to represent different possible Account Statuses (there are other finite data sets that I will be setting up using a duplicate approach):

  • A, Active
  • I, Inactive
  • P, Pending

Those Account Statuses must be presented to the user in their language if preference.

Example: Account Status is A, show it as Active for English speakers and Activo for Spanish.

There are also situations where I would like to show a dropdown list of all possible Account Statuses in the appropriate locale preference.


Current Approach

Use an AccountStatusEnum class with values of (A,I,P).

In a private static member variable store an EnumMap of localized Account Statuses inside a EnumMap of possible Locales.

Example:

private static EnumMap<LocaleEnum, EnumMap<AccountStatusEnum, String>> localeAccountStatuses = new EnumMap<LocaleEnum, EnumMap<AccountStatusEnum, String>>(LocaleEnum.class);

This would get loaded within a static initialization block.

I could then use the following methods to get all the values for a dropdown:

public static EnumMap<AccountStatusEnum, String> getAccountStatuses(LocaleEnum locale) {
        return localeAccountStatuses.get(locale);
    }

Or I could use this method to get a single description for a given Enum:

public String getDescription(LocaleEnum locale){
            return getAccountStatuses(locale).get(this);
        }

Example Usage: AccountStatusEnum.A.getDescription(LocaleEnum.es_MX);

I’m curious about your thoughts on this approach and possible better approaches for accomplishing the same thing.

EDIT
The logic to get the values to populate the Enums would be centralized within a single helper class. Therefore if the source of the descriptions changes to come from a new source, the code change is minimized.

Thanks

I would approach this problem as I would approach any localization issue: ResourceBundle. I use a class called I18n that has a static method called getMessage that takes a key and optionally a list of arguments. The key gets looked up in a ResourceBundle configured to use the default Locale or whatever you prefer (specifics here aren’t important, so long as the caller to I18n doesn’t have to know about what the Locale is).

The I18n class is as follows:

public final class I18n {
    private I18n() {
    }

    private static ResourceBundle bundle;

    public static String getMessage(String key) {
        if(bundle == null) {
            bundle = ResourceBundle.getBundle("path.to.i18n.messages");
        }
        return bundle.getString(key);
    }

    public static String getMessage(String key, Object ... arguments) {
        return MessageFormat.format(getMessage(key), arguments);
    }
}

In your project, you would have in package path.to.i18n, files containing messages.properties (default), messages_en.properties (Locale en), messages_it.properties (Locale it), etc.

When you need to translate an enum value, you shouldn’t have to treat it any differently than any other key, except the key is the enum term.

In other words, you have:

public enum AccountStatusEnum {
  Active,
  Inactive,
  Pending
}

When you call I18n.getMessage, you pass with AccountStatusEnum.Active.toString() and the translation will be found in a property file with key “Active”. If you’re like me, and you prefer to use lower-case keys, then you should perform toLowerCase() on the string. Better still, you create a new I18n.getMessage that takes an Enum rather than a key, and that method calls the String version of I18n.getMessage with the enum value converted to string and in lowercase.

So you’d then add this to the I18n class:

    public static String getMessage(Enum<?> enumVal) {
        return getMessage(enumVal.toString().toLowerCase());
    }

I prefer to use this method because it incorporates the same translation logic in the same part of the program without impacting your design. You may even want to differentiate enum keys from your other keys, in which case you can begin each enum key with “enum.”, so you would prepend “enum.” when calling getMessage. Just remember to name your keys in your properties files accordingly.

I hope that helps!

1

ResourceBundle is the way to go, but I would take advantage of the fact that enums are objects, and hide the details of i19n inside

public enum MyEnum {
  A,
  I,
  P;

  private String localeText = null;

  private MyEnum() {
    // Load resource bundle
    this.localeText = // get message;
  }

  public String getLocaleText() {
    return this.localeText();
  }
}

That would allow you to do:

MyEnum.A.getLocaleText();

directly, everywhere

An optimization would be loading the resource bundle as an static attribute, in an static initializer.

And in JEE, bonus points for making the resource bundle injectable (so you may change the localization strings easily).

14

Summing up pros and cons of the proposed answers:

The problem with the global helper file is the lack of flexibility, for example, in an application I have various enums with a specific enum constant that I would like to have a very specific key, not following the common format.

The problem with locating the logic in the enums is the replication of code, which in turn would make it harder to maintain in the long run

With Java 8 we have at our disposal a very helpful feature that can be very helpful in solving the problems discussed above: default methods.

My proposal is to have an interface with a single method to obtain the keys:

public interface I18nEnum {
   default String getMessageKey(Enum<?> e) {
      return e.getClass().getSimpleName() + '.' + e.name().toLowerCase();
   }
}

That way our enums simply have to declare they implement that interface, without actually implementing it, and we have the benefits of having our code in a single place, but we still have the flexibility to handle specific cases by overriding the default method when needed, for example:

public enum Sex implements I18nEnum {
    MALE,
    FEMALE,
    UNKNOWN {
        @Override
        public String getMessageKey(Enum<?> e) {
            return "Common.UNKNOWN";
        }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật