Properties.storeToXML方法抛出空指针哦!

今天项目里遇到的, 在这里做个记录!

类似下面这段代码:
<!--<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 " );
    }

在生成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;
    }

原来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再使用不是更好吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值