Trước hết, tôi tự hỏi tại sao bạn đã chọn java.util.ResourceBundle
qua java.util.Properties
. Với câu hỏi của bạn được xây dựng như thế nào, bạn dường như không quan tâm đến việc bản địa hóa/quốc tế hóa cũng như về việc thừa kế tệp gói.
Với Properties
thật dễ dàng vì nó thực hiện Map
, do đó cung cấp phương thức putAll()
để hợp nhất một bản đồ khác. Kickoff dụ:
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.
Nếu bạn thực sự nhấn mạnh trong việc sử dụng ResourceBundle
, đặt cược tốt nhất của bạn là tạo ra một tùy chỉnh ResourceBundle
trong đó bạn contol tải bởi một tùy chỉnh Control
.
Giả sử rằng bạn đã nhập cảnh sau trong master.properties
đại diện cho một chuỗi commaseparated với tên cơ sở của các tập tin thuộc tính mô-đun:
include=moduleA,moduleB
Rồi sau tùy chỉnh ResourceBundle
dụ nên làm việc:
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;
}
}
}
(xử lý ngoại lệ tầm thường và xử lý bản địa hóa được để sang một bên, điều này tùy thuộc vào bạn)
.210
này có thể được sử dụng như:
ResourceBundle bundle = new MultiResourceBundle("master");
đau đớn hơn để làm cho tất cả những sửa đổi trong một tập tin duy nhất, vấn đề là với thời gian dev và không có thời gian chạy – Jason