THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

works for Acme, Inc. The longest possible search would be:


GlobalRes_eo_KI_left
GlobalRes_eo_KI
GlobalRes_eo
GlobalRes_ne_BT_Acme
GlobalRes_ne_BT
GlobalRes_ne
GlobalRes


The first resource bundle that is found ends the search, being considered the best available match.


The examples you have seen use resource bundles to fetch strings, but remember that you can use
getObject to get any type of object. Bundles are used to store images, URLs, audio sources, graphics
components, and any other kind of locale-sensitive resource that can be represented by an object.


Mapping string keys to localized resource objects is usually straightforwardsimply use one of the provided
subclasses of ResourceBundle that implement the lookup for you: ListResourceBundle and
PropertyResourceBundle.


24.2.1. ListResourceBundle


ListResourceBundle maps a simple list of keys to their localized objects. It is an abstract subclass of
ResourceBundle for which you provide a getContents method that returns an array of key/resource
pairs as an array of arrays of Object. The keys must be strings, but the resources can be any kind of object.
The ListResourceBundle takes this array and builds the maps for the various "get" methods. The
following classes use ListResourceBundle to define a few locales for GlobalRes. First, the base
bundle:


public class GlobalRes extends ListResourceBundle {
public static final String HELLO = "hello";
public static final String GOODBYE = "goodbye";


public Object[][] getContents() {
return contents;
}


private static final Object[][] contents = {
{ GlobalRes.HELLO, "Ciao" },
{ GlobalRes.GOODBYE, "Ciao" },
};
}


This is the top-level bundlewhen no other bundle is found, this will be used. We have chosen Italian for the
default. Before any "get" method is executed, GlobalRes.getContents will be invoked and the
contents array's values will seed the data structures used by the "get" methods. ListResourceBundle
uses an internal lookup table for efficient access; it does not search through your array of keys. The
GlobalRes class also defines the constants that name known resources in the bundle. Here is another bundle
for a more specific locale:


public class GlobalRes_en extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}

Free download pdf