gpt4 book ai didi

java - PropertyResourceBundle 与 ListResourceBundle 冲突

转载 作者:行者123 更新时间:2023-12-01 10:32:29 26 4
gpt4 key购买 nike

尝试使用以下代码在 Java 8 中加载 TestResourceBundle.properties 文件时:

ResourceBundle resources = ResourceBundle.getBundle("TestResourceBundle");

我意识到,如果类路径中存在一个同名的 ListResourceBundle 类(TestResourceBundle.class),如下所示:

public class TestResourceBundle extends ListResourceBundle {

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

private Object[][] contents = {
{ "Test", "Value2" }
};
}

ListResourceBundle 类的优先级始终高于属性文件,最后加载 ListResourceBundle 类。

这是标准行为吗?

如果我想加载一个属性文件资源包,并且不知道类路径中是否存在同名的ListResourceBundle,该怎么办?

如何确保始终加载属性文件而不是同名的资源包类文件?

最佳答案

在 ResourceBundle.Control 类中,有一个 FORMAT_DEFAULT 列表,该列表始终为类资源包提供比属性文件更高的优先级:

 public static final List<String> FORMAT_DEFAULT
= Collections.unmodifiableList(Arrays.asList("java.class",
"java.properties"));

我们可以更改优先级顺序,覆盖 ResourceBundle.Control 类的 getFormats() 方法,如以下代码所示:

 ResourceBundle resources = ResourceBundle.getBundle("TestResourceBundle", new ResourceBundle.Control() {

@Override
public List<String> getFormats(String baseName) {

if (baseName == null) {
throw new NullPointerException();
}

return Collections.unmodifiableList(Arrays.asList("java.properties", "java.class"));
}

});

关于java - PropertyResourceBundle 与 ListResourceBundle 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35015384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com