开发者

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 constru开发者_开发知识库ctor? 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):

  • https://bugs.eclipse.org/328951.

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

  • http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜