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



Properties对象包含键值对的映射,此外还包含一个";默认值";受保护的Properties字段

可以经由keySet()对密钥进行迭代以获得当前Properties的属性密钥,并且还经由stringPropertyNames()来获得所有不同的密钥;默认值";Properties

我想写一个方法,在给定Properties实例的情况下,返回这些";默认值";,包括键和值。

stringPropertyNames()进行迭代并跳过包括在keySet()中的值是不够的;默认值";可以被当前CCD_ 10中的条目隐藏。访问受保护的";默认值";字段viareflection将显示警告输出,并且可能在未来的java版本中不起作用。

Properties.clone()方法将创建一个新的Properties对象,其中包括默认值。这个克隆可以被清空;默认值":

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;
}

最新更新