为什么在使用get时,Properties对象总是忽略默认值?

不应该对Properties对象调用get方法;而应该调用getProperty方法。
许多人认为二者的区别是getProperty声明了返回值为String类型,而get声明的返回值类型为Object。
但实际上二者之间有更大的区别:getProperty会查看默认值。
get是继承自Hashtable的方法,它会忽视默认值,所以get的职责就像Hashtable文档中描述的一样,但是这种方式可能会跟你想象中的不一样。其它继承自Hashtable的方法也会忽略默认值(如isEmpty和toString方法),举个例子:

 1 Properties defaults = new Properties();
 2 
 3 defaults.put("color", "black");
 4 
 5 System.out.println(props.get("color") + ", " + props.getProperty("color"));
 6 
 7 // 输出: "black, black"
 8 
 9 Properties props = new Properties(defaults);
10 
11 System.out.println(props.get("color") + ", " + props.getProperty("color"));
12 
13 // 输出: "null, black"

这点在文档中有描述么?可能吧。Hashtable的文档中提到了table的实体,同时提到了如果你认为默认值不是表中实体的话,那么Properties的行为是与Hashtable一致的。如果出于某些原因,你认为默认值是表中的实体(正如你会以为能得到与getProperty一样的效果)那你就晕了。

posted on 2016-11-17 20:18  胡子就不刮  阅读(369)  评论(0编辑  收藏  举报

导航