Search code examples
javaresourcesinternationalizationbundleresourcebundle

How to load resource bundle messages from DB in Java?


Can I load a resource bundle dynamically? Can I edit a resource bundle dynamically?

It would be best if I can have such a logical resource bundle (i.e. located in context not as physical file).

Related:

How to load a resource bundle from a file resource?


Solution

  • Would you be able to override the ListResourceBundle? It provides an extension point for adding in your own Object[][] of resource key pairs.

    From the javadoc:

    public class MyResources extends ListResourceBundle {
         protected Object[][] getContents() {
             return new Object[][] = {
             // LOCALIZE THIS
                 {"s1", "The disk \"{1}\" contains {0}."},  // MessageFormat pattern
                 {"s2", "1"},                               // location of {0} in pattern
                 {"s3", "My Disk"},                         // sample disk name
                 {"s4", "no files"},                        // first ChoiceFormat choice
                 {"s5", "one file"},                        // second ChoiceFormat choice
                 {"s6", "{0,number} files"},                // third ChoiceFormat choice
                 {"s7", "3 Mar 96"},                        // sample date
                 {"s8", new Dimension(1,5)}                 // real object, not just string
             // END OF MATERIAL TO LOCALIZE
             };
         }
     }
    

    This example returns a hard coded listing but you can modify that to return whatever you want from a database or anything else.