问题描述
|
Properties defaults = new Properties();
defaults.put(\"color\",\"black\");
Properties props = new Properties(defaults);
// This prints \"null,black\"
System.out.println(props.get(\"color\") + \",\" + props.getProperty(color));
解决方法
Java不幸地做出了使
Properties
子类变为Hashtable
的决定,而不是仅仅包含Hashtable
。
getProperty
方法使用默认的后缀Properties
,但从Hashtable
继承的get
方法却没有。因此,如果您写:
System.out.println(props.getProperty(\"color\"));
它将按照您的预期打印\“ black \”。
, get public V get(Object key)
从HashMap继承的方法。
返回指定键所映射到的值;如果此映射不包含键的映射关系,则返回null。
当使用构造函数new Property(默认)时,将内部字段default设置为默认属性。当在默认属性中使用getProperty属性类查找时,如果Properties HashMap不包含值,则从中返回值。
public String getProperty(String key) {
Object oval = super.get(key);
String sval = (oval instanceof String) ? (String)oval : null;
return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
}