Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What JAXB needs a public no-arg constructor for?

Tags:

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?

like image 884
yegor256 Avatar asked Nov 11 '10 14:11

yegor256


People also ask

Why do we need no-arg constructor?

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.

Does Jackson need all args constructor?

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.

What constructor is required by all objects that are to be marshalled Unmarshalled by Jackson?

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.

What is a default no-arg constructor?

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.


2 Answers

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
like image 139
bdoughan Avatar answered Oct 18 '22 09:10

bdoughan


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");
}
like image 23
David Moles Avatar answered Oct 18 '22 08:10

David Moles