繁体   English   中英

unmarshalled类的属性设置器中的jaxb异常管理

[英]jaxb exception management in property setters of unmarshalled class

当我将Xml节点解组为属性时,将调用setMyProperty。 属性setter的代码可能引发异常:在这种情况下会发生什么?

我观察到的行为:如果异常是未经检查的异常,那么jaxb“internals”会吞下它,并忽略该属性。 如果在Exception中更改了RuntimeException(如此检查并添加到属性setter的throws子句),则会导致unmarshal失败。

问题是:这是一种你可以依赖的行为吗? 在此感谢Agostino

PS:Ok“swallowed”不是正确的单词,因为它实际上是以“最佳方式”进行管理,正确地解组文档的其余部分。 然而,unmarshall调用者不会被通知异常发生。

PS:一个简单的测试用例,以防万一:-)

package test.jaxb;

import java.io.File;
import javax.xml.bind.*;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class SZL {
    public static void main(String [] args) throws JAXBException {

        SZL test = new SZL();
        test.myProp = "test-value";
        test.setMyProp2("test-value-2");

        JAXBContext jc = JAXBContext.newInstance(SZL.class);

        File f = new File("SZL.xml");
        Marshaller m = jc.createMarshaller();
        m.marshal(test, f);

        test = null;
        Unmarshaller um = jc.createUnmarshaller();
        test = (SZL)um.unmarshal(f);

        System.out.println("The RuntimeException has been swallowed");
        System.out.println(test.myProp);
        System.out.println(test.myProp2);

    }

    private String myProp;
    public void setMyProp(String myProp) {
        throw new RuntimeException();
        //this.myProp = myProp;
    }

    public String getMyProp() {return myProp;}

    private String myProp2;
    public void setMyProp2(String myProp2){
        this.myProp2 = myProp2;
    }
    public String getMyProp2() {return myProp2;}

}

不保证在所有JAXB实现( MetroEclipseLink MOXyApache JaxMe等)中都可以移植此行为。

例如,EclipseLink JAXB(MOXy)中不会吞下异常。 注意我是MOXy的领导者,也是JAXB( JSR-222 )专家组的成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM