今天項(xiàng)目里遇到的, 在這里做個(gè)記錄!

類似下面這段代碼:
????@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的時(shí)候會拋出IOException. 導(dǎo)致這個(gè)IOException的是做XMLTransform的時(shí)候出現(xiàn)了NullPointerException

感覺很奇怪, 調(diào)試進(jìn)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啊.

結(jié)果在XMLTransform的時(shí)候, 直接對這個(gè)NULL進(jìn)行方法調(diào)用.

后來看了一下Properties文檔, Properties繼承至Hashtable, 所以有put和putAll之類的方法. 但是不建議使用,
因?yàn)檫@些方法不限定String類型. 推薦使用setProperty方法, 這個(gè)方法的值一定是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,我承認(rèn)是我不好好看文檔就用了. 但是我腳的如果你把非String的值調(diào)用一下toString再使用不是更好嗎?