Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a Java class which implements Serializable interface from xsd using JAXB?

Tags:

java

jaxb

xsd

xjc

I would like to introduce caching into an existing Spring project which uses JAXB to expose WebServices. Caching will be done on the level of end points. In order to do that classes generated from XSD using JAXB need to implement Serializable interface and override Object's toString() method.

How to instruct the xjc tool using XSD to generate source with needed properties?

like image 699
Boris Pavlović Avatar asked Oct 03 '09 15:10

Boris Pavlović


People also ask

How can we make class as Serializable in Java?

To make a Java object serializable you implement the java. io. Serializable interface. This is only a marker interface which tells the Java platform that the object is serializable.

How can we implement Serializable interface?

Serialization is done using ObjectOutputStream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. Deserialization is done using ObjectInputStream.


1 Answers

Serializable

Use xjc:serializable in a custom bindings file to add the java.io.Serializable interface to your classes along with a serialVersionUID:

<?xml version="1.0" encoding="UTF-8"?> <bindings xmlns="http://java.sun.com/xml/ns/jaxb"             xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"             xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"             xsi:schemaLocation=" http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd" version="2.1">   <globalBindings>     <serializable uid="1" />   </globalBindings> </bindings>  

toString()

Use a superclass (see xjc:superClass) from which all your bound classes will inherit. This class won’t be generated by xjc so you are free to create it as you please (here with a toString() implementation):

<?xml version="1.0" encoding="UTF-8"?> <bindings xmlns="http://java.sun.com/xml/ns/jaxb"                 xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"                 xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"                 xsi:schemaLocation=" http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"     version="2.1">     <globalBindings>         <serializable uid="1" />         <xjc:superClass name="the.package.to.my.XmlSuperClass" />     </globalBindings> </bindings> 
like image 51
Pascal Thivent Avatar answered Sep 27 '22 23:09

Pascal Thivent