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?
The arguments of a constructor can only be found by type, not by name, so there is no way for the framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.
11.2. Jackson won't use a constructor with arguments by default, you'd need to tell it to do so with the @JsonCreator annotation. By default it tries to use the no-args constructor which isn't present in your class.
The existence of a no-arg constructor gets validated during creation of the JAXBContext and therefore applies regardless if you want to use JAXB for marshalling or unmarshalling.
1. No-argument constructor: A constructor that has no parameter is known as the default constructor. If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With