今天項目里遇到的, 在這里做個記錄!

類似下面這段代碼:
????@Test(expected?=?IOException.class)
????
public?void?testPropertiesStoreToXml()?throws?IOException?{
????????Properties?props?
=?new?Properties();
????????props.put(
"key1",?true);
????????ByteArrayOutputStream?baos?
=?new?ByteArrayOutputStream();
????????props.storeToXML(baos,
null);
????????String?xml?
=?new?String(baos.toByteArray());
????????Assert.fail(
"should?not?go?to?here");
????}

在生成XML的時候會拋出IOException. 導致這個IOException的是做XMLTransform的時候出現了NullPointerException

感覺很奇怪, 調試進Properties的代碼看了一下.

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

原來Properties這貨, 不是String的屬性一碼色的返回NULL啊.

結果在XMLTransform的時候, 直接對這個NULL進行方法調用.

后來看了一下Properties文檔, Properties繼承至Hashtable, 所以有put和putAll之類的方法. 但是不建議使用,
因為這些方法不限定String類型. 推薦使用setProperty方法, 這個方法的值一定是String.

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a "compromised" Properties object that contains a non-String key.

OK,我承認是我不好好看文檔就用了. 但是我腳的如果你把非String的值調用一下toString再使用不是更好嗎?