ResourceBundle - 属性 文件继承

ResourceBundle - property files inheritance

我正在设置 ResourceBundle,但我得到了违反 Oracle 文档的奇怪结果。 https://docs.oracle.com/cd/E23095_01/Platform.93/ATGProgGuide/html/s1804resourcebundleinheritance01.html

我有 3 个文件:

Animals_fr.properties

name=animals_fr

Animals_en.propertis

name=animals_en
age=5

Animals.properties

name=animals
age=0

然后我有代码:

Locale localeFr = new Locale("fr");
Locale.setDefault(new Locale("en","US"));
ResourceBundle b = ResourceBundle.getBundle("Animals", localeFr);
System.out.println(b.getString("name"));
System.out.println(b.getString("age"));

基于Oracle文档继承应该是这样的:

Animals_fr - locale bundle
Animals_en - default locale bundle
Animals - default bundle

结果应该是:

animals_fr
5

但我得到的结果是:

animals_fr
0

知道哪里出了问题吗?

谢谢

您链接的文档描述了如何查找资源包,而不是如何解析单个资源键。

这与 documented default behavior 匹配,即

If the specified locale's language, script, country, and variant are all empty strings, then the base name is the only candidate bundle name. Otherwise, a list of candidate locales is generated from the attribute values of the specified locale (language, script, country and variant) and appended to the base name.

描述了单个 Locale 如何产生一系列候选名称。在您的情况下,它只是 [ Animal_Fr ]。然后,它说:

This continues until a result resource bundle is instantiated or the list of candidate bundle names is exhausted. If no matching resource bundle is found, the default control's getFallbackLocale method is called, which returns the current default locale. A new sequence of candidate locale names is generated using this locale and and searched again, as above.

因此,如果 Animal_Fr 不存在,它会回退到默认语言环境,尝试使用 [ Animals_en_US, Animals_en ].

的候选序列

但是由于Animal_Fr确实存在并且可以被实例化,所以这个查找不会继续下去。相反,对于查找特定的资源密钥,链接变得相关,记录为:

Once a result resource bundle has been found, its parent chain is instantiated. If the result bundle already has a parent (perhaps because it was returned from a cache) the chain is complete.

Otherwise, getBundle examines the remainder of the candidate locale list that was used during the pass that generated the result resource bundle. […] When it comes to the end of the candidate list, it tries the plain bundle name. With each of the candidate bundle names it attempts to instantiate a resource bundle […].

Whenever it succeeds, it calls the previously instantiated resource bundle's setParent method with the new resource bundle. This continues until the list of names is exhausted or the current bundle already has a non-null parent.

因此链接文档关于 getBundle 的整体行为是正确的,这是文档中描述的两步过程的结果。但是当涉及到与getString行为相关的父链时,只会使用当前查找阶段的候选列表。

因此,根据实际存在的捆绑包,它可能会以以下任一方式结束

Animals_fr ‣ Animals

Animals_en_US ‣ Animals_en ‣ Animals

在您的示例设置中。