2

I have to add little bussiness logic in my jaxb generated classes. For example, I have following XMLs:

<vehicle>
 <car id="20" make="ABC"/>
</vehicle>

<vehicle>
 <motorcycle id="05" make="XYZ"/>
<vehicle>

<vehicle>
 <truck id="34"  make="UVW"/>
</vehicle>

And I generate XSD for these.

Now what I have to achieve is during unmarshalling of any XML of these type (that is whenever setters of car, motorcycle or truck is envoked, it should also set the vehicle type which I don't want to add as an attribute in the XML).

Or after unmarshalling (any way by which I can know the QName of sub element). I have tried How can I extend Java code generated by JAXP-cxf or Hibernate tools?, but the overriden setters were never called.

Community
  • 1
  • 1
shaguar
  • 53
  • 5

2 Answers2

1

JAXB has a "post construct" facility (see javadoc). Just add something like this to your annotated class:

void afterUnmarshal(Unmarshaller, Object parent) {
    vehicle.setType(..); // your logic here    
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • now after i have unmarshalled the XML i have received a vehicle object and inside it i have either car,motorcycle or truck type of object.How to know wich of these is present? – shaguar Feb 12 '11 at 17:52
  • I also thought of that but didn't add it because he said "JAXB generated clases", so I assumed his clases are generated on each build. But it might be "generated once" – Bozho Feb 12 '11 at 18:01
0

You can create a JAXB extension. But that sounds like an overhead to me - you could simple invoke an initializer whenever you unmarshal a JAXB object. Something like:

public class Initializer {
    public static void initialize(Vehicle vehicle) {
       vehicle.setType(..); // your logic here
    }
}

And call Initializer.initialize(unmarshalledObject)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • what type of initializer to invoke, and does JAXB supports it? – shaguar Feb 12 '11 at 11:57
  • I mean, external initializer. – Bozho Feb 12 '11 at 12:15
  • can you please provide a sample code for that, actually i am new to all this.Thanks in advance – shaguar Feb 12 '11 at 12:45
  • but Bozho,how will i know from the unmarshalledObject which vehicle type i have inside the vehicle object. Actually the problem can be stated as How to know which of the subtypes(car,truck or motorcycle) is present in the unmarshalled vehicle object . – shaguar Feb 12 '11 at 17:51