简体   繁体   中英

What JAXB needs a public no-arg constructor for?

What does JAXB need a public no-arg constructor for, during marshalling?

 Marshaller msh = ctx.createMarshaller();
 msh.marshal(object, System.out);

I'm passing an object, not a class. Why does JAXB need a constructor? To construct what?

A JAXB implementation should not need a no-arg constructor during a marshal operation. JAXB does require one for unmarshalling. Normally the absence of a no-arg constructor causes an error when the JAXBContext is created. The JAXB implementation you are using may be delaying initialization until an actual operation is performed.

In general support for multi-arg constructors is something we should consider in a future version of JAXB. In the EclipseLink implementation of JAXB (MOXy) we have an enhancement request open for this functionality (feel free to add relevant details):

In the current version of JAXB you could use an XmlAdapter to support this use case:

As others have noted, it shouldn't really need one but (at least in Sun's implementation) it does. You can get around this with a dummy constructor:

private MyObject() {
    throw new UnsupportedOperationException("No-arg constructor is just to keep JAXB from complaining");
}

The same as many frameworks - simplicity and consistency. It allows the library to simple call Class.newInstance() without having to worry about how to specify certain dependencies for a constructor that takes them. JAXB doesn't want to concern itself with full-on Dependency Injection above and beyond the attribute-based setting it already does.

It's a shame in some ways as it means these classes can't be immutable, but that's the trade-off to be made.

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