Java Reference
In-Depth Information
Example 10•22: GUIResourceBundle.java (continued)
/** A hashtable for mapping resource types to resource parsers */
static HashMap parsers = new HashMap();
/** An extension mechanism: register a parser for new resource types */
public static void registerResourceParser(ResourceParser parser) {
// Ask the ResourceParser what types it can parse
Class[] supportedTypes = parser.getResourceTypes();
// Register it in the hashtable for each of those types
for(int i = 0; i < supportedTypes.length; i++)
parsers.put(supportedTypes[i], parser);
}
/** Look up a ResourceParser for the specified resource type */
public static ResourceParser getResourceParser(Class type) {
return (ResourceParser) parsers.get(type);
}
/**
* Look for a ResourceParser for the named type, and if one is found,
* ask it to parse and return the named resource
**/
public Object getResource(String key, Class type)
throws MissingResourceException
{
// Get a parser for the specified type
ResourceParser parser = (ResourceParser)parsers.get(type);
if (parser == null)
throw new MissingResourceException(
"No ResourceParser registered for " +
type.getName() + " resources",
type.getName(), key);
try { // Ask the parser to parse the resource
return parser.parse(this, key, type);
}
catch(MissingResourceException e) {
throw e; // Rethrow MissingResourceException exceptions
}
catch(Exception e) {
// If any other type of exception occurs, convert it to
// a MalformedResourceException
String msg = "Malformed " + type.getName() + " resource: " +
key + ": " + e.getMessage();
throw new MalformedResourceException(msg, type.getName(), key);
}
}
/**
* Like the 2-argument version of getResource, but return a default value
* instead of throwing a MissingResourceException
**/
public Object getResource(String key, Class type, Object defaultValue) {
try { return getResource(key, type); }
catch (MissingResourceException e) {
if (e instanceof MalformedResourceException)
System.err.println("WARNING: " + e.getMessage());
return defaultValue;
}
Search WWH ::




Custom Search