resourcebundle.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 1,150 行 · 第 1/4 页

JAVA
1,150
字号
    /**     * Gets a resource bundle using the specified base name and locale,     * and the caller's class loader. Calling this method is equivalent to calling     * <blockquote>     * <code>getBundle(baseName, locale, this.getClass().getClassLoader())</code>,     * </blockquote>     * except that <code>getClassLoader()</code> is run with the security     * privileges of <code>ResourceBundle</code>.     * See {@link #getBundle(java.lang.String, java.util.Locale, java.lang.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 java.lang.NullPointerException     *     if <code>baseName</code> or <code>locale</code> is <code>null</code>     * @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     */    public static final ResourceBundle getBundle(String baseName,                                                         Locale locale)    {        return getBundleImpl(baseName, locale, getLoader());    }    /**     * Gets a resource bundle using the specified base name, locale, and class loader.     *     * <p>     * Conceptually, <code>getBundle</code> uses the following strategy for locating and instantiating     * resource bundles:     * <p>     * <code>getBundle</code> 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 <em>candidate bundle names</em>.     * 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):     * <ul>     * <li> baseName + "_" + language1 + "_" + country1 + "_" + variant1     * <li> baseName + "_" + language1 + "_" + country1     * <li> baseName + "_" + language1     * <li> baseName + "_" + language2 + "_" + country2 + "_" + variant2     * <li> baseName + "_" + language2 + "_" + country2     * <li> baseName + "_" + language2     * <li> baseName     * </ul>     * <p>     * 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.     *     * <p>     * <code>getBundle</code> then iterates over the candidate bundle names to find the first     * one for which it can <em>instantiate</em> an actual resource bundle. For each candidate     * bundle name, it attempts to create a resource bundle:     * <ul>     * <li>     * 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,     * <code>getBundle</code> creates a new instance of this class and uses it as the <em>result     * resource bundle</em>.     * <li>     * Otherwise, <code>getBundle</code> 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 <code>getResource</code> 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 <em>result resource bundle</em>.     * </ul>     *     * <p>     * If no result resource bundle has been found, a <code>MissingResourceException</code>     * is thrown.     *     * <p>     * Once a result resource bundle has been found, its parent chain is instantiated.     * <code>getBundle</code> 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.     *     * <p>     * Implementations of <code>getBundle</code> may cache instantiated resource bundles     * and return the same resource bundle instance multiple times. They may also     * vary the sequence in which resource bundles are instantiated as long as the     * selection of the result resource bundle and its parent chain are compatible with     * the description above.     *     * <p>     * The <code>baseName</code> argument should be a fully qualified class name. However, for     * compatibility with earlier versions, Sun's Java 2 runtime environments do not verify this,     * and so it is possible to access <code>PropertyResourceBundle</code>s by specifying a     * path name (using "/") instead of a fully qualified class name (using ".").     *     * <p>     * <strong>Example:</strong> The following class and property files are provided:     * MyResources.class, MyResources_fr_CH.properties, MyResources_fr_CH.class,     * MyResources_fr.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 <code>Locale("en", "GB")</code>.     * <p>     * Calling <code>getBundle</code> with the shown locale argument values instantiates     * resource bundles from the following sources:     * <ul>     * <li>Locale("fr", "CH"): result MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class     * <li>Locale("fr", "FR"): result MyResources_fr.properties, parent MyResources.class     * <li>Locale("de", "DE"): result MyResources_en.properties, parent MyResources.class     * <li>Locale("en", "US"): result MyResources_en.properties, parent MyResources.class     * <li>Locale("es", "ES"): result MyResources_es_ES.class, parent MyResources.class     * </ul>     * The file MyResources_fr_CH.properties is never used because it is hidden by     * MyResources_fr_CH.class.     *     * <p>     *     * @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     * @exception java.lang.NullPointerException     *     if <code>baseName</code>, <code>locale</code>, or <code>loader</code> is <code>null</code>     * @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     * @since 1.2     */    public static ResourceBundle getBundle(String baseName, Locale locale,                                           ClassLoader loader)    {        if (loader == null) {            throw new NullPointerException();        }        return getBundleImpl(baseName, locale, loader);    }    private static ResourceBundle getBundleImpl(String baseName, Locale locale,                                           ClassLoader loader)    {        if (baseName == null) {            throw new NullPointerException();        }        //fast path the case where the bundle is cached        String bundleName = baseName;        String localeSuffix = locale.toString();        if (localeSuffix.length() > 0) {            bundleName += "_" + localeSuffix;        } else if (locale.getVariant().length() > 0) {            //This corrects some strange behavior in Locale where            //new Locale("", "", "VARIANT").toString == ""            bundleName += "___" + locale.getVariant();        }                // The default locale may influence the lookup result, and        // it may change, so we get it here once.        Locale defaultLocale = Locale.getDefault();        Object lookup = findBundleInCache(loader, bundleName, defaultLocale);        if (lookup == NOT_FOUND) {            throwMissingResourceException(baseName, locale);        } else if (lookup != null) {            return (ResourceBundle)lookup;        }        //The bundle was not cached, so start doing lookup at the root        //Resources are loaded starting at the root and working toward        //the requested bundle.        //If findBundle returns null, we become responsible for defining        //the bundle, and must call putBundleInCache to complete this        //task.  This is critical because other threads may be waiting        //for us to finish.        Object parent = NOT_FOUND;        try {            //locate the root bundle and work toward the desired child            Object root = findBundle(loader, baseName, defaultLocale, baseName, null);            if (root == null) {                putBundleInCache(loader, baseName, defaultLocale, NOT_FOUND);                root = NOT_FOUND;            }            // Search the main branch of the search tree.            // We need to keep references to the bundles we find on the main path            // so they don't get garbage collected before we get to propagate().            final Vector names = calculateBundleNames(baseName, locale);            Vector bundlesFound = new Vector(MAX_BUNDLES_SEARCHED);	    // if we found the root bundle and no other bundle names are needed	    // we can stop here. We don't need to search or load anything further.            boolean foundInMainBranch = (root != NOT_FOUND && names.size() == 0);	    	    if (!foundInMainBranch) {	      parent = root;	      for (int i = 0; i < names.size(); i++) {                bundleName = (String)names.elementAt(i);                lookup = findBundle(loader, bundleName, defaultLocale, baseName, parent);                bundlesFound.addElement(lookup);                if (lookup != null) {                    parent = lookup;                    foundInMainBranch = true;                }	      }            }            parent = root;            if (!foundInMainBranch) {                //we didn't find anything on the main branch, so we do the fallback branch                final Vector fallbackNames = calculateBundleNames(baseName, defaultLocale);                for (int i = 0; i < fallbackNames.size(); i++) {                    bundleName = (String)fallbackNames.elementAt(i);                    if (names.contains(bundleName)) {                        //the fallback branch intersects the main branch so we can stop now.                        break;                    }                    lookup = findBundle(loader, bundleName, defaultLocale, baseName, parent);                    if (lookup != null) {                        parent = lookup;                    } else {                        //propagate the parent to the child.  We can do this                        //here because we are in the default path.                        putBundleInCache(loader, bundleName, defaultLocale, parent);                    }                }            }            //propagate the inheritance/fallback down through the main branch            parent = propagate(loader, names, bundlesFound, defaultLocale, parent);        } catch (Exception e) {            //We should never get here unless there has been a change            //to the code that doesn't catch it's own exceptions.            cleanUpConstructionList();            throwMissingResourceException(baseName, locale);        } catch (Error e) {            //The only Error that can currently hit this code is a ThreadDeathError            //but errors might be added in the future, so we'll play it safe and            //clean up.            cleanUpConstructionList();            throw e;        }        if (parent == NOT_FOUND) {            throwMissingResourceException(baseName, locale);        }        return (ResourceBundle)parent;    }    /**     * propagate bundles from the root down the specified branch of the search tree.     * @param loader the class loader for the bundles     * @param names the names of the bundles along search path     * @param bundlesFound the bundles corresponding to the names (some may be null)     * @param defaultLocale the default locale at the time getBundle was called     * @param parent the parent of the first bundle in the path (the root bundle)     * @return the value of the last bundle along the path     */    private static Object propagate(ClassLoader loader, Vector names,            Vector bundlesFound, Locale defaultLocale, Object parent) {        for (int i = 0; i < names.size(); i++) {            final String bundleName = (String)names.elementAt(i);            final Object lookup = bundlesFound.elementAt(i);            if (lookup == null) {                putBundleInCache(loader, bundleName, defaultLocale, parent);            } else {                parent = lookup;            }        }        return parent;    }    /** Throw a MissingResourceException with proper message */    private static void throwMissingResourceException(String baseName, Locale locale)            throws MissingResourceException{        throw new MissingResourceException("Can't find bundle for base name "                                           + baseName + ", locale " + locale,                                           baseName + "_" + locale,"");    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?