[ Team LiB ] Previous Section Next Section

Recipe 24.4 Creating a ResourceBundle as a Java Class


You want to create a ResourceBundle as a Java class.


Create a class that extends java.util.ListResourceBundle.


If your application requires more functionality than a static properties file can provide (Recipe 24.3), you can create your ResourceBundles as Java classes: java.util.ListResourceBundle types. For instance, a particular resource might need to select its translation information from a database.

Example 24-4 includes the same information as the properties file in the prior recipe. However, its key/value pairs are stored in the form of a two-dimensional Object array. This class is stored in the same place as the .properties files in WEB-INF/i18n.

Example 24-4. Storing language information in a ListResourceBundle
package com.jspservletcookbook;           

import java.util.ListResourceBundle;
public class WelcomeBundle_es_ES extends ListResourceBundle {
         static final Object[][] contents = {
         {"Welcome", "Hola y recepción"}
         public Object[][] getContents( ) {
         return contents;

This code snippet from a servlet shows how you could use this class.

Example 24-5. Calling a ListResourceBundle method from a ResourceBundle created as a Java class
<!-- inside servlet goGet( ) or doPost( ) method, for instance -->

ResourceBundle bundle = ResourceBundle.getBundle(

//Call inherited ListResourceBundle getKeys( ) method
java.util.Enumeration enum = bundle.getKeys( );

while (enum.hasMoreElements( )){
    //Prints out key: "Welcome"
    out.println((String) enum.nextElement( ));
    out.println("<br /><br />");

The ResourceBundle.getBundle( ) static method tries to find a Java class with the fully qualified name "i18n.WelcomeBundle_es_ES" (in this example). Failing that, it looks for a properties file of the same name (minus the .properties extension): i18n.WelcomeBundle_es_ES.properties.

See Also

The Javadoc for ListResourceBundle: http://java.sun.com/j2se/1.4.1/docs/api/java/util/ListResourceBundle.html; Recipe 24.3 on creating a ResourceBundle as a properties file.

    [ Team LiB ] Previous Section Next Section