首先,我想知道为什么您选择
java.util.ResourceBundle了
java.util.Properties。给出问题的表达方式后,您似乎不必关心本地化/国际化或捆绑文件继承。
有了
Properties它,它就变得异常容易,因为它实现
Map了反过来又提供了
putAll()一种合并另一张地图的方法。开球示例:
Properties master = new Properties();master.load(masterInput);Properties moduleA = new Properties();moduleA.load(moduleAinput);master.putAll(moduleA);Properties moduleB = new Properties();moduleB.load(moduleBinput);master.putAll(moduleB);// Now `master` contains the properties of all files.
如果您真的坚持使用
ResourceBundle,则最好的选择是创建一个自定义
ResourceBundle,在该自定义中使用自定义控制加载
Control。
假设您具有以下条目,
master.properties其中表示一个以逗号分隔的字符串,带有模块属性文件的基本名称:
include=moduleA,moduleB
然后,以下自定义
ResourceBundle示例应该起作用:
public class MultiResourceBundle extends ResourceBundle { protected static final Control ConTROL = new MultiResourceBundleControl(); private Properties properties; public MultiResourceBundle(String baseName) { setParent(ResourceBundle.getBundle(baseName, CONTROL)); } protected MultiResourceBundle(Properties properties) { this.properties = properties; } @Override protected Object handleGetObject(String key) { return properties != null ? properties.get(key) : parent.getObject(key); } @Override @SuppressWarnings("unchecked") public Enumeration<String> getKeys() { return properties != null ? (Enumeration<String>) properties.propertyNames() : parent.getKeys(); } protected static class MultiResourceBundleControl extends Control { @Override public ResourceBundle newBundle( String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { Properties properties = load(baseName, loader); String include = properties.getProperty("include"); if (include != null) { for (String includebaseName : include.split("\s*,\s*")) { properties.putAll(load(includebaseName, loader)); } } return new MultiResourceBundle(properties); } private Properties load(String baseName, ClassLoader loader) throws IOException { Properties properties = new Properties(); properties.load(loader.getResourceAsStream(baseName + ".properties")); return properties; } }}(忽略异常处理和本地化处理,这取决于您)
可以用作:
ResourceBundle bundle = new MultiResourceBundle("master");


