Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a default constructor required for objects exported by a JAX-WS?

JAX-WS requires that all classes that are transmitted have a default contructor (no-arg constructor). I do not understand that requirement because clients create their own classes based on the WSDL. IMO this requirement makes sense only for those classes that are used as input parameters of the Webservice.

Does anyone know how to circumvent that requirement?

like image 486
Stefan Avatar asked Jul 11 '12 09:07

Stefan


1 Answers

When you use JAX-WS you are using a JAXB implementation to serialize your java objects to XML.

So, the 'problem' is how JAXB works.

To use JAXB, you need to create a JAXBContext passing it all the classes that can be marshaled/unmarshaled. When creating the context, JAXB will check that all the given classes have a no-arg constructor. If at least one of those classes does not have this kind of constructor, the context will not be created.

Why JAXB do this? It needs this no-arg constructor ONLY when transforming from XML to Object (unmarshalling), but the issue is when you are creating the context, JAXB does not know what you want to do (marshal or unmarshal)!

Conclusion: JAXB will accept only classes that it can marshal AND unmarshal. More info here

Knowing this, what happen in JAX-WS?

When you declare a @WebMethod the parameters and return value classes will be added to a JAXB context. And is because of this that all the classes related to a web service input and output needs a no-arg constructor.

Conclusion: is JAXB fault ;-)

But what if I need to use a class that does not have a no-arg constructor?

You can use an XMLAdapter! Check this post for more info ...

like image 190
ggarciao Avatar answered Sep 28 '22 08:09

ggarciao