今天项目里遇到的, 在这里做个记录!
类似下面这段代码:
@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再使用不是更好吗?