简体   繁体   English

如何从 java.util.Properties 获取默认值

[英]How to get the defaults from java.util.Properties

A Properties object contains a map of key-value pairs and additionally a "defaults" Properties field that is protected .一个Properties object 包含一个 map 的键值对,另外还有一个protected的“defaults” Properties字段。

One can iterate over the keys via keySet() to get the property keys of the current Properties , and also via stringPropertyNames() to get all distinct keys including the keys within the "defaults" Properties .可以通过keySet()遍历键以获取当前Properties的属性键,也可以通过stringPropertyNames()获取所有不同的键,包括“默认” Properties中的键。

I would like to write a method that, given a Properties instance, returns these "defaults", including the keys and values.我想编写一个方法,给定一个Properties实例,返回这些“默认值”,包括键和值。

Iterating the stringPropertyNames() and skipping values that are included in keySet() is not sufficient, since the entries in the "defaults" may be hidden by entries in the current Properties .迭代stringPropertyNames()并跳过keySet()中包含的值是不够的,因为“默认值”中的条目可能被当前Properties中的条目隐藏。 Accessing the protected "defaults" field via reflection will show a warning output and may not work in future java versions.通过反射访问受保护的“默认值”字段将显示警告 output 并且可能在未来的 java 版本中不起作用。

The Properties.clone() method will create a new Properties object including the defaults. Properties.clone()方法将创建一个新的Properties object,包括默认值。 This clone can be emptied and what's left are the "defaults":这个克隆可以清空,剩下的是“默认值”:

public static Properties getDefaultProperties(final Properties properties) {
    // use a clone to not modify the supplied properties
    final Properties clone = (Properties) properties.clone();
    // since we cannot access the default properties, we simply remove all non-default
    clone.clear();
    // what remains are the default properties that we will copy
    final Properties defaultProperties = new Properties();
    for (final String property : clone.stringPropertyNames()) {
        defaultProperties.setProperty(property, clone.getProperty(property));
    }
    return defaultProperties;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM