今天项目里遇到的, 在这里做个记录!
类似下面这段代码:
在生成XML的时候会抛出IOException. 导致这个IOException的是做XMLTransform的时候出现了NullPointerException
感觉很奇怪, 调试进Properties的代码看了一下.
原来Properties这货, 不是String的属性一码色的返回NULL啊.
结果在XMLTransform的时候, 直接对这个NULL进行方法调用.
后来看了一下Properties文档, Properties继承至Hashtable, 所以有put和putAll之类的方法. 但是不建议使用,
因为这些方法不限定String类型. 推荐使用setProperty方法, 这个方法的值一定是String.
Because
OK,我承认是我不好好看文档就用了. 但是我脚的如果你把非String的值调用一下toString再使用不是更好吗?
类似下面这段代码:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> @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");
}
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的代码看了一下.
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> 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;
}
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再使用不是更好吗?
本文探讨了使用Java的Properties类存储非字符串值到XML时出现的IOException问题。通过调试发现,当使用非字符串类型的值存储时,会在XML转换过程中引发NullPointerException。文章详细解释了这一现象的原因,并给出了正确的做法。
2884

被折叠的 条评论
为什么被折叠?



