FileDocCategorySizeDatePackage
ResourceBundle.javaAPI DocJava SE 6 API106823Tue Jun 10 00:25:54 BST 2008java.util

ResourceBundle

public abstract class ResourceBundle extends Object
Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user's locale. In this way, you can write program code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles.

This allows you to write programs that can:

  • be easily localized, or translated, into different languages
  • handle multiple locales at once
  • be easily modified later to support even more locales

Resource bundles belong to families whose members share a common base name, but whose names also have additional components that identify their locales. For example, the base name of a family of resource bundles might be "MyResources". The family should have a default resource bundle which simply has the same name as its family - "MyResources" - and will be used as the bundle of last resort if a specific locale is not supported. The family can then provide as many locale-specific members as needed, for example a German one named "MyResources_de".

Each resource bundle in a family contains the same items, but the items have been translated for the locale represented by that resource bundle. For example, both "MyResources" and "MyResources_de" may have a String that's used on a button for canceling operations. In "MyResources" the String may contain "Cancel" and in "MyResources_de" it may contain "Abbrechen".

If there are different resources for different countries, you can make specializations: for example, "MyResources_de_CH" contains objects for the German language (de) in Switzerland (CH). If you want to only modify some of the resources in the specialization, you can do so.

When your program needs a locale-specific object, it loads the ResourceBundle class using the {@link #getBundle(java.lang.String, java.util.Locale) getBundle} method:

ResourceBundle myResources =
ResourceBundle.getBundle("MyResources", currentLocale);

Resource bundles contain key/value pairs. The keys uniquely identify a locale-specific object in the bundle. Here's an example of a ListResourceBundle that contains two key/value pairs:

public class MyResources extends ListResourceBundle {
protected Object[][] getContents() {
return new Object[][] {
// LOCALIZE THE SECOND STRING OF EACH ARRAY (e.g., "OK")
{"OkKey", "OK"},
{"CancelKey", "Cancel"},
// END OF MATERIAL TO LOCALIZE
};
}
}
Keys are always Strings. In this example, the keys are "OkKey" and "CancelKey". In the above example, the values are also Strings--"OK" and "Cancel"--but they don't have to be. The values can be any type of object.

You retrieve an object from resource bundle using the appropriate getter method. Because "OkKey" and "CancelKey" are both strings, you would use getString to retrieve them:

button1 = new Button(myResources.getString("OkKey"));
button2 = new Button(myResources.getString("CancelKey"));
The getter methods all require the key as an argument and return the object if found. If the object is not found, the getter method throws a MissingResourceException.

Besides getString, ResourceBundle also provides a method for getting string arrays, getStringArray, as well as a generic getObject method for any other type of object. When using getObject, you'll have to cast the result to the appropriate type. For example:

int[] myIntegers = (int[]) myResources.getObject("intList");

The Java Platform provides two subclasses of ResourceBundle, ListResourceBundle and PropertyResourceBundle, that provide a fairly simple way to create resources. As you saw briefly in a previous example, ListResourceBundle manages its resource as a list of key/value pairs. PropertyResourceBundle uses a properties file to manage its resources.

If ListResourceBundle or PropertyResourceBundle do not suit your needs, you can write your own ResourceBundle subclass. Your subclasses must override two methods: handleGetObject and getKeys().

ResourceBundle.Control

The {@link ResourceBundle.Control} class provides information necessary to perform the bundle loading process by the getBundle factory methods that take a ResourceBundle.Control instance. You can implement your own subclass in order to enable non-standard resource bundle formats, change the search strategy, or define caching parameters. Refer to the descriptions of the class and the {@link #getBundle(String, Locale, ClassLoader, Control) getBundle} factory method for details.

Cache Management

Resource bundle instances created by the getBundle factory methods are cached by default, and the factory methods return the same resource bundle instance multiple times if it has been cached. getBundle clients may clear the cache, manage the lifetime of cached resource bundle instances using time-to-live values, or specify not to cache resource bundle instances. Refer to the descriptions of the {@linkplain #getBundle(String, Locale, ClassLoader, Control) getBundle factory method}, {@link #clearCache(ClassLoader) clearCache}, {@link Control#getTimeToLive(String, Locale) ResourceBundle.Control.getTimeToLive}, and {@link Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle, long) ResourceBundle.Control.needsReload} for details.

Example

The following is a very simple example of a ResourceBundle subclass, MyResources, that manages two resources (for a larger number of resources you would probably use a Map). Notice that you don't need to supply a value if a "parent-level" ResourceBundle handles the same key with the same value (as for the okKey below).
// default (English language, United States)
public class MyResources extends ResourceBundle {
public Object handleGetObject(String key) {
if (key.equals("okKey")) return "Ok";
if (key.equals("cancelKey")) return "Cancel";
return null;
}

public Enumeration<String> getKeys() {
return Collections.enumeration(keySet());
}

// Overrides handleKeySet() so that the getKeys() implementation
// can rely on the keySet() value.
protected Set<String> handleKeySet() {
return new HashSet<String>(Arrays.asList("okKey", "cancelKey"));
}
}

// German language
public class MyResources_de extends MyResources {
public Object handleGetObject(String key) {
// don't need okKey, since parent level handles it.
if (key.equals("cancelKey")) return "Abbrechen";
return null;
}

protected Set<String> handleKeySet() {
return new HashSet<String>(Arrays.asList("cancelKey"));
}
}
You do not have to restrict yourself to using a single family of ResourceBundles. For example, you could have a set of bundles for exception messages, ExceptionResources (ExceptionResources_fr, ExceptionResources_de, ...), and one for widgets, WidgetResource (WidgetResources_fr, WidgetResources_de, ...); breaking up the resources however you like.
see
ListResourceBundle
see
PropertyResourceBundle
see
MissingResourceException
since
JDK1.1

Fields Summary
private static final int
INITIAL_CACHE_SIZE
initial size of the bundle cache
private static final ResourceBundle
NONEXISTENT_BUNDLE
constant indicating that no resource bundle exists
private static final ConcurrentMap
cacheList
The cache is a map from cache keys (with bundle base name, locale, and class loader) to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a BundleReference. The cache is a ConcurrentMap, allowing the cache to be searched concurrently by multiple threads. This will also allow the cache keys to be reclaimed along with the ClassLoaders they reference. This variable would be better named "cache", but we keep the old name for compatibility with some workarounds for bug 4212439.
private static final ConcurrentMap
underConstruction
This ConcurrentMap is used to keep multiple threads from loading the same bundle concurrently. The table entries are where CacheKey is the key for the bundle that is under construction and Thread is the thread that is constructing the bundle. This list is manipulated in findBundleInCache and putBundleInCache.
private static final ReferenceQueue
referenceQueue
Queue for reference objects referring to class loaders or bundles.
protected ResourceBundle
parent
The parent bundle of this bundle. The parent bundle is searched by {@link #getObject getObject} when this bundle does not contain a particular resource.
private Locale
locale
The locale for this bundle.
private String
name
The base bundle name for this bundle.
private volatile boolean
expired
The flag indicating this bundle has expired in the cache.
private volatile CacheKey
cacheKey
The back link to the cache key. null if this bundle isn't in the cache (yet) or has expired.
private volatile Set
keySet
A Set of the keys contained only in this ResourceBundle.
Constructors Summary
public ResourceBundle()
Sole constructor. (For invocation by subclass constructors, typically implicit.)


                   
      
    
Methods Summary
private static final booleanbeginLoading(java.util.ResourceBundle$CacheKey constKey)
Declares the beginning of actual resource bundle loading. This method returns true if the declaration is successful and the current thread has been put in underConstruction. If someone else has already begun loading, this method waits until that loading work is complete and returns false.

	Thread me = Thread.currentThread();
	Thread worker;
	// We need to declare by putting the current Thread (me) to
	// underConstruction that we are working on loading the specified
	// resource bundle. If we are already working the loading, it means
	// that the resource loading requires a recursive call. In that case,
	// we have to proceed. (4300693)
	if (((worker = underConstruction.putIfAbsent(constKey, me)) == null)
	    || worker == me) {
	    return true;
	}

	// If someone else is working on the loading, wait until
	// the Thread finishes the bundle loading.
	synchronized (worker) {
	    while (underConstruction.get(constKey) == worker) {
		try {
		    worker.wait();
		} catch (InterruptedException e) {
		    // record the interruption
		    constKey.setCause(e);
		}
	    }
	}
	return false;
    
private static final booleancheckList(java.util.List a)
Checks if the given List is not null, not empty, not having null in its elements.

	boolean valid = (a != null && a.size() != 0);
	if (valid) {
	    int size = a.size();
	    for (int i = 0; valid && i < size; i++) {
		valid = (a.get(i) != null);
	    }
	}
	return valid;
    
public static final voidclearCache()
Removes all resource bundles from the cache that have been loaded using the caller's class loader.

since
1.6
see
ResourceBundle.Control#getTimeToLive(String,Locale)

	clearCache(getLoader());
    
public static final voidclearCache(java.lang.ClassLoader loader)
Removes all resource bundles from the cache that have been loaded using the given class loader.

param
loader the class loader
exception
NullPointerException if loader is null
since
1.6
see
ResourceBundle.Control#getTimeToLive(String,Locale)

	if (loader == null) {
	    throw new NullPointerException();
	}
	Set<CacheKey> set = cacheList.keySet();
	for (CacheKey key : set) {
	    if (key.getLoader() == loader) {
		set.remove(key);
	    }
	}
    
public booleancontainsKey(java.lang.String key)
Determines whether the given key is contained in this ResourceBundle or its parent bundles.

param
key the resource key
return
true if the given key is contained in this ResourceBundle or its parent bundles; false otherwise.
exception
NullPointerException if key is null
since
1.6

	if (key == null) {
	    throw new NullPointerException();
	}
	for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
	    if (rb.handleKeySet().contains(key)) {
		return true;
	    }
	}
	return false;
    
private static final voidendLoading(java.util.ResourceBundle$CacheKey constKey)
Declares the end of the bundle loading. This method calls notifyAll for those who are waiting for this completion.

	// Remove this Thread from the underConstruction map and wake up
	// those who have been waiting for me to complete this bundle
	// loading.
	Thread me = Thread.currentThread();
	assert (underConstruction.get(constKey) == me);
	underConstruction.remove(constKey);
	synchronized (me) {
	    me.notifyAll();
	}
    
private static final java.util.ResourceBundlefindBundle(java.util.ResourceBundle$CacheKey cacheKey, java.util.List candidateLocales, java.util.List formats, int index, java.util.ResourceBundle$Control control, java.util.ResourceBundle baseBundle)

	Locale targetLocale = candidateLocales.get(index);
	ResourceBundle parent = null;
	if (index != candidateLocales.size() - 1) {
	    parent = findBundle(cacheKey, candidateLocales, formats, index + 1,
				control, baseBundle);
	} else if (baseBundle != null && Locale.ROOT.equals(targetLocale)) {
	    return baseBundle;
	}

	// Before we do the real loading work, see whether we need to
	// do some housekeeping: If references to class loaders or
	// resource bundles have been nulled out, remove all related
	// information from the cache.
	Object ref;
	while ((ref = referenceQueue.poll()) != null) {
	    cacheList.remove(((CacheKeyReference)ref).getCacheKey());
	}

	// flag indicating the resource bundle has expired in the cache
	boolean expiredBundle = false;

	// First, look up the cache to see if it's in the cache, without
	// declaring beginLoading.
	cacheKey.setLocale(targetLocale);
	ResourceBundle bundle = findBundleInCache(cacheKey, control);
	if (isValidBundle(bundle)) {
	    expiredBundle = bundle.expired;
	    if (!expiredBundle) {
		// If its parent is the one asked for by the candidate
		// locales (the runtime lookup path), we can take the cached
		// one. (If it's not identical, then we'd have to check the
		// parent's parents to be consistent with what's been
		// requested.)
		if (bundle.parent == parent) {
		    return bundle;
		}
		// Otherwise, remove the cached one since we can't keep
		// the same bundles having different parents.
		BundleReference bundleRef = cacheList.get(cacheKey);
		if (bundleRef != null && bundleRef.get() == bundle) {
		    cacheList.remove(cacheKey, bundleRef);
		}
	    }
	}

	if (bundle != NONEXISTENT_BUNDLE) {
	    CacheKey constKey = (CacheKey) cacheKey.clone();

	    try {
		// Try declaring loading. If beginLoading() returns true,
		// then we can proceed. Otherwise, we need to take a look
		// at the cache again to see if someone else has loaded
		// the bundle and put it in the cache while we've been
		// waiting for other loading work to complete.
		while (!beginLoading(constKey)) {
		    bundle = findBundleInCache(cacheKey, control);
		    if (bundle == null) {
			continue;
		    }
		    if (bundle == NONEXISTENT_BUNDLE) {
			// If the bundle is NONEXISTENT_BUNDLE, the bundle doesn't exist.
			return parent;
		    }
		    expiredBundle = bundle.expired;
		    if (!expiredBundle) {
			if (bundle.parent == parent) {
			    return bundle;
			}
			BundleReference bundleRef = cacheList.get(cacheKey);
			if (bundleRef != null && bundleRef.get() == bundle) {
			    cacheList.remove(cacheKey, bundleRef);
			}
		    }
		}

		try {
		    bundle = loadBundle(cacheKey, formats, control, expiredBundle);
		    if (bundle != null) {
			if (bundle.parent == null) {
			    bundle.setParent(parent);
			}
			bundle.locale = targetLocale;
			bundle = putBundleInCache(cacheKey, bundle, control);
			return bundle;
		    }

		    // Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle
		    // instance for the locale.
		    putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control);
		} finally {
		    endLoading(constKey);
		}
	    } finally {
		if (constKey.getCause() instanceof InterruptedException) {
		    Thread.currentThread().interrupt();
		}
	    }
	}
	assert underConstruction.get(cacheKey) != Thread.currentThread();
	return parent;
    
private static final java.util.ResourceBundlefindBundleInCache(java.util.ResourceBundle$CacheKey cacheKey, java.util.ResourceBundle$Control control)
Finds a bundle in the cache. Any expired bundles are marked as `expired' and removed from the cache upon return.

param
cacheKey the key to look up the cache
param
control the Control to be used for the expiration control
return
the cached bundle, or null if the bundle is not found in the cache or its parent has expired. bundle.expire is true upon return if the bundle in the cache has expired.

	BundleReference bundleRef = cacheList.get(cacheKey);
	if (bundleRef == null) {
	    return null;
	}
	ResourceBundle bundle = bundleRef.get();
	if (bundle == null) {
	    return null;
	}
	ResourceBundle p = bundle.parent;
	assert p != NONEXISTENT_BUNDLE;
	// If the parent has expired, then this one must also expire. We
	// check only the immediate parent because the actual loading is
	// done from the root (base) to leaf (child) and the purpose of
	// checking is to propagate expiration towards the leaf. For
	// example, if the requested locale is ja_JP_JP and there are
	// bundles for all of the candidates in the cache, we have a list,
	//
	// base <- ja <- ja_JP <- ja_JP_JP
	//
	// If ja has expired, then it will reload ja and the list becomes a
	// tree.
	//
	// base <- ja (new)
	//  "   <- ja (expired) <- ja_JP <- ja_JP_JP
	//
	// When looking up ja_JP in the cache, it finds ja_JP in the cache
	// which references to the expired ja. Then, ja_JP is marked as
	// expired and removed from the cache. This will be propagated to
	// ja_JP_JP.
	//
	// Now, it's possible, for example, that while loading new ja_JP,
	// someone else has started loading the same bundle and finds the
	// base bundle has expired. Then, what we get from the first
	// getBundle call includes the expired base bundle. However, if
	// someone else didn't start its loading, we wouldn't know if the
	// base bundle has expired at the end of the loading process. The
	// expiration control doesn't guarantee that the returned bundle and
	// its parents haven't expired.
	//
	// We could check the entire parent chain to see if there's any in
	// the chain that has expired. But this process may never end. An
	// extreme case would be that getTimeToLive returns 0 and
	// needsReload always returns true.
	if (p != null && p.expired) {
	    assert bundle != NONEXISTENT_BUNDLE;
	    bundle.expired = true;
	    bundle.cacheKey = null;
	    cacheList.remove(cacheKey, bundleRef);
	    bundle = null;
	} else {
	    CacheKey key = bundleRef.getCacheKey();
	    long expirationTime = key.expirationTime;
	    if (!bundle.expired && expirationTime >= 0 &&
		expirationTime <= System.currentTimeMillis()) {
		// its TTL period has expired.
		if (bundle != NONEXISTENT_BUNDLE) {
		    // Synchronize here to call needsReload to avoid
		    // redundant concurrent calls for the same bundle.
		    synchronized (bundle) {
			expirationTime = key.expirationTime;
			if (!bundle.expired && expirationTime >= 0 &&
			    expirationTime <= System.currentTimeMillis()) {
			    try {
				bundle.expired = control.needsReload(key.getName(),
								     key.getLocale(),
								     key.getFormat(),
								     key.getLoader(),
								     bundle,
								     key.loadTime);
			    } catch (Exception e) {
				cacheKey.setCause(e);
			    }
			    if (bundle.expired) {
				// If the bundle needs to be reloaded, then
				// remove the bundle from the cache, but
				// return the bundle with the expired flag
				// on.
				bundle.cacheKey = null;
				cacheList.remove(cacheKey, bundleRef);
			    } else {
				// Update the expiration control info. and reuse
				// the same bundle instance
				setExpirationTime(key, control);
			    }
			}
		    }
		} else {
		    // We just remove NONEXISTENT_BUNDLE from the cache.
		    cacheList.remove(cacheKey, bundleRef);
		    bundle = null;
		}
	    }
	}
	return bundle;
    
public static final java.util.ResourceBundlegetBundle(java.lang.String baseName, java.util.ResourceBundle$Control control)
Returns a resource bundle using the specified base name, the default locale and the specified control. Calling this method is equivalent to calling
getBundle(baseName, Locale.getDefault(),
this.getClass().getClassLoader(), control),
except that getClassLoader() is run with the security privileges of ResourceBundle. See {@link #getBundle(String, Locale, ClassLoader, Control) getBundle} for the complete description of the resource bundle loading process with a ResourceBundle.Control.

param
baseName the base name of the resource bundle, a fully qualified class name
param
control the control which gives information for the resource bundle loading process
return
a resource bundle for the given base name and the default locale
exception
NullPointerException if baseName or control is null
exception
MissingResourceException if no resource bundle for the specified base name can be found
exception
IllegalArgumentException if the given control doesn't perform properly (e.g., control.getCandidateLocales returns null.) Note that validation of control is performed as needed.
since
1.6

	return getBundleImpl(baseName, Locale.getDefault(),
			     /* must determine loader here, else we break stack invariant */
			     getLoader(),
			     control);
    
public static final java.util.ResourceBundlegetBundle(java.lang.String baseName, java.util.Locale locale)
Gets a resource bundle using the specified base name and locale, and the caller's class loader. Calling this method is equivalent to calling
getBundle(baseName, locale, this.getClass().getClassLoader()),
except that getClassLoader() is run with the security privileges of ResourceBundle. See {@link #getBundle(String, Locale, ClassLoader) getBundle} for a complete description of the search and instantiation strategy.

param
baseName the base name of the resource bundle, a fully qualified class name
param
locale the locale for which a resource bundle is desired
exception
NullPointerException if baseName or locale is null
exception
MissingResourceException if no resource bundle for the specified base name can be found
return
a resource bundle for the given base name and locale

        return getBundleImpl(baseName, locale,
			     /* must determine loader here, else we break stack invariant */
			     getLoader(),
			     Control.INSTANCE);
    
public static final java.util.ResourceBundlegetBundle(java.lang.String baseName, java.util.Locale targetLocale, java.util.ResourceBundle$Control control)
Returns a resource bundle using the specified base name, target locale and control, and the caller's class loader. Calling this method is equivalent to calling
getBundle(baseName, targetLocale, this.getClass().getClassLoader(),
control),
except that getClassLoader() is run with the security privileges of ResourceBundle. See {@link #getBundle(String, Locale, ClassLoader, Control) getBundle} for the complete description of the resource bundle loading process with a ResourceBundle.Control.

param
baseName the base name of the resource bundle, a fully qualified class name
param
targetLocale the locale for which a resource bundle is desired
param
control the control which gives information for the resource bundle loading process
return
a resource bundle for the given base name and a Locale in locales
exception
NullPointerException if baseName, locales or control is null
exception
MissingResourceException if no resource bundle for the specified base name in any of the locales can be found.
exception
IllegalArgumentException if the given control doesn't perform properly (e.g., control.getCandidateLocales returns null.) Note that validation of control is performed as needed.
since
1.6

	return getBundleImpl(baseName, targetLocale,
			     /* must determine loader here, else we break stack invariant */
			     getLoader(),
			     control);
    
public static java.util.ResourceBundlegetBundle(java.lang.String baseName, java.util.Locale locale, java.lang.ClassLoader loader)
Gets a resource bundle using the specified base name, locale, and class loader.

Conceptually, getBundle uses the following strategy for locating and instantiating resource bundles:

getBundle uses the base name, the specified locale, and the default locale (obtained from {@link java.util.Locale#getDefault() Locale.getDefault}) to generate a sequence of candidate bundle names. If the specified locale's language, country, and variant are all empty strings, then the base name is the only candidate bundle name. Otherwise, the following sequence is generated from the attribute values of the specified locale (language1, country1, and variant1) and of the default locale (language2, country2, and variant2):

  • baseName + "_" + language1 + "_" + country1 + "_" + variant1
  • baseName + "_" + language1 + "_" + country1
  • baseName + "_" + language1
  • baseName + "_" + language2 + "_" + country2 + "_" + variant2
  • baseName + "_" + language2 + "_" + country2
  • baseName + "_" + language2
  • baseName

Candidate bundle names where the final component is an empty string are omitted. For example, if country1 is an empty string, the second candidate bundle name is omitted.

getBundle then iterates over the candidate bundle names to find the first one for which it can instantiate an actual resource bundle. For each candidate bundle name, it attempts to create a resource bundle:

  • First, it attempts to load a class using the candidate bundle name. If such a class can be found and loaded using the specified class loader, is assignment compatible with ResourceBundle, is accessible from ResourceBundle, and can be instantiated, getBundle creates a new instance of this class and uses it as the result resource bundle.
  • Otherwise, getBundle attempts to locate a property resource file. It generates a path name from the candidate bundle name by replacing all "." characters with "/" and appending the string ".properties". It attempts to find a "resource" with this name using {@link java.lang.ClassLoader#getResource(java.lang.String) ClassLoader.getResource}. (Note that a "resource" in the sense of getResource has nothing to do with the contents of a resource bundle, it is just a container of data, such as a file.) If it finds a "resource", it attempts to create a new {@link PropertyResourceBundle} instance from its contents. If successful, this instance becomes the result resource bundle.

If no result resource bundle has been found, a MissingResourceException is thrown.

Once a result resource bundle has been found, its parent chain is instantiated. getBundle iterates over the candidate bundle names that can be obtained by successively removing variant, country, and language (each time with the preceding "_") from the bundle name of the result resource bundle. As above, candidate bundle names where the final component is an empty string are omitted. With each of the candidate bundle names it attempts to instantiate a resource bundle, as described above. Whenever it succeeds, it calls the previously instantiated resource bundle's {@link #setParent(java.util.ResourceBundle) setParent} method with the new resource bundle, unless the previously instantiated resource bundle already has a non-null parent.

getBundle caches instantiated resource bundles and may return the same resource bundle instance multiple times.

The baseName argument should be a fully qualified class name. However, for compatibility with earlier versions, Sun's Java SE Runtime Environments do not verify this, and so it is possible to access PropertyResourceBundles by specifying a path name (using "/") instead of a fully qualified class name (using ".").

Example:
The following class and property files are provided:

MyResources.class
MyResources.properties
MyResources_fr.properties
MyResources_fr_CH.class
MyResources_fr_CH.properties
MyResources_en.properties
MyResources_es_ES.class
The contents of all files are valid (that is, public non-abstract subclasses of ResourceBundle for the ".class" files, syntactically correct ".properties" files). The default locale is Locale("en", "GB").

Calling getBundle with the shown locale argument values instantiates resource bundles from the following sources:

  • Locale("fr", "CH"): result MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class
  • Locale("fr", "FR"): result MyResources_fr.properties, parent MyResources.class
  • Locale("de", "DE"): result MyResources_en.properties, parent MyResources.class
  • Locale("en", "US"): result MyResources_en.properties, parent MyResources.class
  • Locale("es", "ES"): result MyResources_es_ES.class, parent MyResources.class

The file MyResources_fr_CH.properties is never used because it is hidden by MyResources_fr_CH.class. Likewise, MyResources.properties is also hidden by MyResources.class.

param
baseName the base name of the resource bundle, a fully qualified class name
param
locale the locale for which a resource bundle is desired
param
loader the class loader from which to load the resource bundle
return
a resource bundle for the given base name and locale
exception
java.lang.NullPointerException if baseName, locale, or loader is null
exception
MissingResourceException if no resource bundle for the specified base name can be found
since
1.2

        if (loader == null) {
            throw new NullPointerException();
        }
        return getBundleImpl(baseName, locale, loader, Control.INSTANCE);
    
public static java.util.ResourceBundlegetBundle(java.lang.String baseName, java.util.Locale targetLocale, java.lang.ClassLoader loader, java.util.ResourceBundle$Control control)
Returns a resource bundle using the specified base name, target locale, class loader and control. Unlike the {@linkplain #getBundle(String, Locale, ClassLoader) getBundle factory methods with no control argument}, the given control specifies how to locate and instantiate resource bundles. Conceptually, the bundle loading process with the given control is performed in the following steps.

  1. This factory method looks up the resource bundle in the cache for the specified baseName, targetLocale and loader. If the requested resource bundle instance is found in the cache and the time-to-live periods of the instance and all of its parent instances have not expired, the instance is returned to the caller. Otherwise, this factory method proceeds with the loading process below.
  2. The {@link ResourceBundle.Control#getFormats(String) control.getFormats} method is called to get resource bundle formats to produce bundle or resource names. The strings "java.class" and "java.properties" designate class-based and {@linkplain PropertyResourceBundle property}-based resource bundles, respectively. Other strings starting with "java." are reserved for future extensions and must not be used for application-defined formats. Other strings designate application-defined formats.
  3. The {@link ResourceBundle.Control#getCandidateLocales(String, Locale) control.getCandidateLocales} method is called with the target locale to get a list of candidate Locales for which resource bundles are searched.
  4. The {@link ResourceBundle.Control#newBundle(String, Locale, String, ClassLoader, boolean) control.newBundle} method is called to instantiate a ResourceBundle for the base bundle name, a candidate locale, and a format. (Refer to the note on the cache lookup below.) This step is iterated over all combinations of the candidate locales and formats until the newBundle method returns a ResourceBundle instance or the iteration has used up all the combinations. For example, if the candidate locales are Locale("de", "DE"), Locale("de") and Locale("") and the formats are "java.class" and "java.properties", then the following is the sequence of locale-format combinations to be used to call control.newBundle.
    Locale
    format
    Locale("de", "DE")
    java.class
    Locale("de", "DE") java.properties
    Locale("de") java.class
    Locale("de") java.properties
    Locale("")
    java.class
    Locale("") java.properties
  5. If the previous step has found no resource bundle, proceed to Step 6. If a bundle has been found that is a base bundle (a bundle for Locale("")), and the candidate locale list only contained Locale(""), return the bundle to the caller. If a bundle has been found that is a base bundle, but the candidate locale list contained locales other than Locale(""), put the bundle on hold and proceed to Step 6. If a bundle has been found that is not a base bundle, proceed to Step 7.
  6. The {@link ResourceBundle.Control#getFallbackLocale(String, Locale) control.getFallbackLocale} method is called to get a fallback locale (alternative to the current target locale) to try further finding a resource bundle. If the method returns a non-null locale, it becomes the next target locale and the loading process starts over from Step 3. Otherwise, if a base bundle was found and put on hold in a previous Step 5, it is returned to the caller now. Otherwise, a MissingResourceException is thrown.
  7. At this point, we have found a resource bundle that's not the base bundle. If this bundle set its parent during its instantiation, it is returned to the caller. Otherwise, its parent chain is instantiated based on the list of candidate locales from which it was found. Finally, the bundle is returned to the caller.

During the resource bundle loading process above, this factory method looks up the cache before calling the {@link Control#newBundle(String, Locale, String, ClassLoader, boolean) control.newBundle} method. If the time-to-live period of the resource bundle found in the cache has expired, the factory method calls the {@link ResourceBundle.Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle, long) control.needsReload} method to determine whether the resource bundle needs to be reloaded. If reloading is required, the factory method calls control.newBundle to reload the resource bundle. If control.newBundle returns null, the factory method puts a dummy resource bundle in the cache as a mark of nonexistent resource bundles in order to avoid lookup overhead for subsequent requests. Such dummy resource bundles are under the same expiration control as specified by control.

All resource bundles loaded are cached by default. Refer to {@link Control#getTimeToLive(String,Locale) control.getTimeToLive} for details.

The following is an example of the bundle loading process with the default ResourceBundle.Control implementation.

Conditions:

  • Base bundle name: foo.bar.Messages
  • Requested Locale: {@link Locale#ITALY}
  • Default Locale: {@link Locale#FRENCH}
  • Available resource bundles: foo/bar/Messages_fr.properties and foo/bar/Messages.properties

First, getBundle tries loading a resource bundle in the following sequence.

  • class foo.bar.Messages_it_IT
  • file foo/bar/Messages_it_IT.properties
  • class foo.bar.Messages_it
  • file foo/bar/Messages_it.properties
  • class foo.bar.Messages
  • file foo/bar/Messages.properties

At this point, getBundle finds foo/bar/Messages.properties, which is put on hold because it's the base bundle. getBundle calls {@link Control#getFallbackLocale(String, Locale) control.getFallbackLocale("foo.bar.Messages", Locale.ITALY)} which returns Locale.FRENCH. Next, getBundle tries loading a bundle in the following sequence.

  • class foo.bar.Messages_fr
  • file foo/bar/Messages_fr.properties
  • class foo.bar.Messages
  • file foo/bar/Messages.properties

getBundle finds foo/bar/Messages_fr.properties and creates a ResourceBundle instance. Then, getBundle sets up its parent chain from the list of the candiate locales. Only foo/bar/Messages.properties is found in the list and getBundle creates a ResourceBundle instance that becomes the parent of the instance for foo/bar/Messages_fr.properties.

param
baseName the base name of the resource bundle, a fully qualified class name
param
targetLocale the locale for which a resource bundle is desired
param
loader the class loader from which to load the resource bundle
param
control the control which gives information for the resource bundle loading process
return
a resource bundle for the given base name and locale
exception
NullPointerException if baseName, targetLocale, loader, or control is null
exception
MissingResourceException if no resource bundle for the specified base name can be found
exception
IllegalArgumentException if the given control doesn't perform properly (e.g., control.getCandidateLocales returns null.) Note that validation of control is performed as needed.
since
1.6

        if (loader == null || control == null) {
            throw new NullPointerException();
        }
        return getBundleImpl(baseName, targetLocale, loader, control);
    
public static final java.util.ResourceBundlegetBundle(java.lang.String baseName)
Gets a resource bundle using the specified base name, the default locale, and the caller's class loader. Calling this method is equivalent to calling
getBundle(baseName, Locale.getDefault(), this.getClass().getClassLoader()),
except that getClassLoader() is run with the security privileges of ResourceBundle. See {@link #getBundle(String, Locale, ClassLoader) getBundle} for a complete description of the search and instantiation strategy.

param
baseName the base name of the resource bundle, a fully qualified class name
exception
java.lang.NullPointerException if baseName is null
exception
MissingResourceException if no resource bundle for the specified base name can be found
return
a resource bundle for the given base name and the default locale

        return getBundleImpl(baseName, Locale.getDefault(),
			     /* must determine loader here, else we break stack invariant */
			     getLoader(),
			     Control.INSTANCE);
    
private static java.util.ResourceBundlegetBundleImpl(java.lang.String baseName, java.util.Locale locale, java.lang.ClassLoader loader, java.util.ResourceBundle$Control control)

	if (locale == null || control == null) {
	    throw new NullPointerException();
	}

	// We create a CacheKey here for use by this call. The base
	// name and loader will never change during the bundle loading
	// process. We have to make sure that the locale is set before
	// using it as a cache key.
	CacheKey cacheKey = new CacheKey(baseName, locale, loader);
	ResourceBundle bundle = null;

	// Quick lookup of the cache.
	BundleReference bundleRef = cacheList.get(cacheKey);
	if (bundleRef != null) {
	    bundle = bundleRef.get();
	    bundleRef = null;
	}

	// If this bundle and all of its parents are valid (not expired),
	// then return this bundle. If any of the bundles is expired, we
	// don't call control.needsReload here but instead drop into the
	// complete loading process below.
	if (isValidBundle(bundle) && hasValidParentChain(bundle)) {
	    return bundle;
	}

        // No valid bundle was found in the cache, so we need to load the
        // resource bundle and its parents.

	boolean isKnownControl = (control == Control.INSTANCE) ||
				   (control instanceof SingleFormatControl);
	List<String> formats = control.getFormats(baseName);
	if (!isKnownControl && !checkList(formats)) {
	    throw new IllegalArgumentException("Invalid Control: getFormats");
	}

	ResourceBundle baseBundle = null;
	for (Locale targetLocale = locale;
	     targetLocale != null;
	     targetLocale = control.getFallbackLocale(baseName, targetLocale)) {
	    List<Locale> candidateLocales = control.getCandidateLocales(baseName, targetLocale);
	    if (!isKnownControl && !checkList(candidateLocales)) {
		throw new IllegalArgumentException("Invalid Control: getCandidateLocales");
	    }

	    bundle = findBundle(cacheKey, candidateLocales, formats, 0, control, baseBundle);

	    // If the loaded bundle is the base bundle and exactly for the
	    // requested locale or the only candidate locale, then take the
	    // bundle as the resulting one. If the loaded bundle is the base
	    // bundle, it's put on hold until we finish processing all
	    // fallback locales.
	    if (isValidBundle(bundle)) {
		boolean isBaseBundle = Locale.ROOT.equals(bundle.locale);
		if (!isBaseBundle || bundle.locale.equals(locale)
		    || (candidateLocales.size() == 1
			&& bundle.locale.equals(candidateLocales.get(0)))) {
		    break;
		}

		// If the base bundle has been loaded, keep the reference in
		// baseBundle so that we can avoid any redundant loading in case
		// the control specify not to cache bundles.
		if (isBaseBundle && baseBundle == null) {
		    baseBundle = bundle;
		}
	    }
	}

	if (bundle == null) {
	    if (baseBundle == null) {
		throwMissingResourceException(baseName, locale, cacheKey.getCause());
	    }
	    bundle = baseBundle;
	}

	return bundle;
    
private static native java.lang.Class[]getClassContext()

public abstract java.util.EnumerationgetKeys()
Returns an enumeration of the keys.

return
an Enumeration of the keys contained in this ResourceBundle and its parent bundles.

private static java.lang.ClassLoadergetLoader()

        Class[] stack = getClassContext();
        /* Magic number 2 identifies our caller's caller */
        Class c = stack[2];
        ClassLoader cl = (c == null) ? null : c.getClassLoader();
        if (cl == null) {
	    // When the caller's loader is the boot class loader, cl is null
	    // here. In that case, ClassLoader.getSystemClassLoader() may
	    // return the same class loader that the application is
	    // using. We therefore use a wrapper ClassLoader to create a
	    // separate scope for bundles loaded on behalf of the Java
	    // runtime so that these bundles cannot be returned from the
	    // cache to the application (5048280).
	    cl = RBClassLoader.INSTANCE;
        }
        return cl;
    
public java.util.LocalegetLocale()
Returns the locale of this resource bundle. This method can be used after a call to getBundle() to determine whether the resource bundle returned really corresponds to the requested locale or is a fallback.

return
the locale of this resource bundle

        return locale;
    
public final java.lang.ObjectgetObject(java.lang.String key)
Gets an object for the given key from this resource bundle or one of its parents. This method first tries to obtain the object from this resource bundle using {@link #handleGetObject(java.lang.String) handleGetObject}. If not successful, and the parent resource bundle is not null, it calls the parent's getObject method. If still not successful, it throws a MissingResourceException.

param
key the key for the desired object
exception
NullPointerException if key is null
exception
MissingResourceException if no object for the given key can be found
return
the object for the given key

        Object obj = handleGetObject(key);
        if (obj == null) {
            if (parent != null) {
                obj = parent.getObject(key);
            }
            if (obj == null)
                throw new MissingResourceException("Can't find resource for bundle "
                                                   +this.getClass().getName()
                                                   +", key "+key,
                                                   this.getClass().getName(),
                                                   key);
        }
        return obj;
    
public final java.lang.StringgetString(java.lang.String key)
Gets a string for the given key from this resource bundle or one of its parents. Calling this method is equivalent to calling
(String) {@link #getObject(java.lang.String) getObject}(key).

param
key the key for the desired string
exception
NullPointerException if key is null
exception
MissingResourceException if no object for the given key can be found
exception
ClassCastException if the object found for the given key is not a string
return
the string for the given key

        return (String) getObject(key);
    
public final java.lang.String[]getStringArray(java.lang.String key)
Gets a string array for the given key from this resource bundle or one of its parents. Calling this method is equivalent to calling
(String[]) {@link #getObject(java.lang.String) getObject}(key).

param
key the key for the desired string array
exception
NullPointerException if key is null
exception
MissingResourceException if no object for the given key can be found
exception
ClassCastException if the object found for the given key is not a string array
return
the string array for the given key

        return (String[]) getObject(key);
    
protected abstract java.lang.ObjecthandleGetObject(java.lang.String key)
Gets an object for the given key from this resource bundle. Returns null if this resource bundle does not contain an object for the given key.

param
key the key for the desired object
exception
NullPointerException if key is null
return
the object for the given key, or null

protected java.util.SethandleKeySet()
Returns a Set of the keys contained only in this ResourceBundle.

The default implementation returns a Set of the keys returned by the {@link #getKeys() getKeys} method except for the ones for which the {@link #handleGetObject(String) handleGetObject} method returns null. Once the Set has been created, the value is kept in this ResourceBundle in order to avoid producing the same Set in the next calls. Override this method in subclass implementations for faster handling.

return
a Set of the keys contained only in this ResourceBundle
since
1.6

	if (keySet == null) {
	    synchronized (this) {
		if (keySet == null) {
		    Set<String> keys = new HashSet<String>();
		    Enumeration<String> enumKeys = getKeys();
		    while (enumKeys.hasMoreElements()) {
			String key = enumKeys.nextElement();
			if (handleGetObject(key) != null) {
			    keys.add(key);
			}
		    }
		    keySet = keys;
		}
	    }
	}
	return keySet;
    
private static final booleanhasValidParentChain(java.util.ResourceBundle bundle)
Determines whether any of resource bundles in the parent chain, including the leaf, have expired.

	long now = System.currentTimeMillis();
	while (bundle != null) {
	    if (bundle.expired) {
		return false;
	    }
	    CacheKey key = bundle.cacheKey;
	    if (key != null) {
		long expirationTime = key.expirationTime;
		if (expirationTime >= 0 && expirationTime <= now) {
		    return false;
		}
	    }
	    bundle = bundle.parent;
	}
	return true;
    
private static final booleanisValidBundle(java.util.ResourceBundle bundle)

	return bundle != null && bundle != NONEXISTENT_BUNDLE;
    
public java.util.SetkeySet()
Returns a Set of all keys contained in this ResourceBundle and its parent bundles.

return
a Set of all keys contained in this ResourceBundle and its parent bundles.
since
1.6

	Set<String> keys = new HashSet<String>();
	for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
	    keys.addAll(rb.handleKeySet());
	}
	return keys;
    
private static final java.util.ResourceBundleloadBundle(java.util.ResourceBundle$CacheKey cacheKey, java.util.List formats, java.util.ResourceBundle$Control control, boolean reload)

	assert underConstruction.get(cacheKey) == Thread.currentThread();

	// Here we actually load the bundle in the order of formats
	// specified by the getFormats() value.
	Locale targetLocale = cacheKey.getLocale();

	ResourceBundle bundle = null;
	int size = formats.size();
	for (int i = 0; i < size; i++) {
	    String format = formats.get(i);
	    try {
		bundle = control.newBundle(cacheKey.getName(), targetLocale, format,
					   cacheKey.getLoader(), reload);
	    } catch (LinkageError error) {
		// We need to handle the LinkageError case due to
		// inconsistent case-sensitivity in ClassLoader.
		// See 6572242 for details.
		cacheKey.setCause(error);
	    } catch (Exception cause) {
		cacheKey.setCause(cause);
	    }
	    if (bundle != null) {
		// Set the format in the cache key so that it can be
		// used when calling needsReload later.
		cacheKey.setFormat(format);
		bundle.name = cacheKey.getName();
		bundle.locale = targetLocale;
		// Bundle provider might reuse instances. So we should make
		// sure to clear the expired flag here.
		bundle.expired = false;
		break;
	    }
	}
	assert underConstruction.get(cacheKey) == Thread.currentThread();

	return bundle;
    
private static final java.util.ResourceBundleputBundleInCache(java.util.ResourceBundle$CacheKey cacheKey, java.util.ResourceBundle bundle, java.util.ResourceBundle$Control control)
Put a new bundle in the cache.

param
cacheKey the key for the resource bundle
param
bundle the resource bundle to be put in the cache
return
the ResourceBundle for the cacheKey; if someone has put the bundle before this call, the one found in the cache is returned.

	setExpirationTime(cacheKey, control);
	if (cacheKey.expirationTime != Control.TTL_DONT_CACHE) {
	    CacheKey key = (CacheKey) cacheKey.clone();
	    BundleReference bundleRef = new BundleReference(bundle, referenceQueue, key);
	    bundle.cacheKey = key;

	    // Put the bundle in the cache if it's not been in the cache.
	    BundleReference result = cacheList.putIfAbsent(key, bundleRef);

	    // If someone else has put the same bundle in the cache before
	    // us and it has not expired, we should use the one in the cache.
	    if (result != null) {
		ResourceBundle rb = result.get();
		if (rb != null && !rb.expired) {
		    // Clear the back link to the cache key
		    bundle.cacheKey = null;
		    bundle = rb;
		    // Clear the reference in the BundleReference so that
		    // it won't be enqueued.
		    bundleRef.clear();
		} else {
		    // Replace the invalid (garbage collected or expired)
		    // instance with the valid one.
		    cacheList.put(key, bundleRef);
		}
	    }
	}
	return bundle;
    
private static final voidsetExpirationTime(java.util.ResourceBundle$CacheKey cacheKey, java.util.ResourceBundle$Control control)

	long ttl = control.getTimeToLive(cacheKey.getName(),
					 cacheKey.getLocale());
	if (ttl >= 0) {
	    // If any expiration time is specified, set the time to be
	    // expired in the cache.
	    long now = System.currentTimeMillis();
	    cacheKey.loadTime = now;
	    cacheKey.expirationTime = now + ttl;
	} else if (ttl >= Control.TTL_NO_EXPIRATION_CONTROL) {
	    cacheKey.expirationTime = ttl;
	} else {
	    throw new IllegalArgumentException("Invalid Control: TTL=" + ttl);
	}
    
protected voidsetParent(java.util.ResourceBundle parent)
Sets the parent bundle of this bundle. The parent bundle is searched by {@link #getObject getObject} when this bundle does not contain a particular resource.

param
parent this bundle's parent bundle.

	assert parent != NONEXISTENT_BUNDLE;
        this.parent = parent;
    
private static final voidthrowMissingResourceException(java.lang.String baseName, java.util.Locale locale, java.lang.Throwable cause)
Throw a MissingResourceException with proper message

	// If the cause is a MissingResourceException, avoid creating
	// a long chain. (6355009)
	if (cause instanceof MissingResourceException) {
	    cause = null;
	}
        throw new MissingResourceException("Can't find bundle for base name "
                                           + baseName + ", locale " + locale,
                                           baseName + "_" + locale, // className
					   "",                      // key
					   cause);