Skip to content
Advertisement

Do I need to convert a resource bundle to a map to access the values or can I directly use the bundle?

Not being too familiar with Java, I may be doing something redundant or unnecessary. I am getting a ResourceBundle and then looking to convert it to a Map and then using values from the map.

This is what I am trying to do …

    try {
        bundle = ResourceBundle.getBundle("filename");
    } catch (MissingResourceException e) {
        ...
        
    } catch (Exception e) {
        ...
    }
    Map<String, String> map = convertResourceBundleToMap (bundle);
    
    // Then else where in the code, to get a value, I do
    map.get(key);

Method to convert the ResourceBundle to Map:

    private static Map<String, String> convertResourceBundleToMap(ResourceBundle resource) {
        Map<String, String> map = new HashMap<>();
    
        Enumeration<String> keys = resource.getKeys();

        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String value = resource.getString(key);
            map.put(key, value);
        
        }
        return map;
    }

Is there a downside to getting the values directly from ResourceBundle with a

resource.getString(key);

call?

Also, how would one do this if it were to be in a multi-threaded environment?

Advertisement

Answer

Unless you have some exotic use-case, you can and should use ResourceBundle methods directly, for the following reasons:

  1. ResourceBundle is specifically designed to be used this way. There are also additional methods available, for example, getStringArray(). You would lose some of the ResourceBundle information if you convert it to a plain map.

  2. ResourceBundle has additional parent-child logic (like Properties). It solves the defaulting problem, when not all strings are translated into every locale. This parent-child relation would be de-normalized when converting to a map.

  3. Conversion to a map is an additional performance and memory overhead which doesn’t bring any significant benefits.

  4. ResourceBundle is thread safe. Default method implementations are thread safe, and the class contract requires all subclasses to be thread-safe.


I could think of converting a ResourceBundle into a map only for some unusual use-cases, like serializing the strings to JSON, or transforming the keys/values somehow.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement