简体   繁体   中英

jaxb exception management in property setters of unmarshalled class

When I unmarshal an Xml node to a property, the setMyProperty is called. The code of the property setter may raise an exception:what happens in this case?

The behaviour that I have observed: if the exception is an unchecked exception, then it is swallowed by jaxb "internals" and that property ignored. If the RuntimeException is changed in a Exception (so checked and added to the throws clause of the property setter) it causes the unmarshal to fail.

The question is: is this a behaviour you can rely on? thanks in advance Agostino

PS: Ok "swallowed" is not the correct word, because it actually is managed in the "best possible way", unmarshalling correctly the rest of the document. Nevertheless the unmarshall caller is not notified that an exception has happen.

PS: A simple test case, just in case :-)

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;}

}

This behaviour is not guaranteed to be portable across all JAXB implementations ( Metro , EclipseLink MOXy , Apache JaxMe , etc).

For example the exception is not swallowed in EclipseLink JAXB (MOXy). Note I'm the MOXy lead, and a member of the JAXB ( JSR-222 ) expert group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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