Search code examples
javapolymorphismxstreamxml-deserialization

How to deserialize an XML file to its own unique class?


I have an XML file which contains an array of Vehicles but I need to be able to deserialize it and take each object and put it in its own Vehicle.

For example this is what my XML file kinda looks like:

<Vehicle-array>
   <Car></Car>
   <Truck></Truck>
   <Van></Van>
</Vehicle-array>

So I need to be able to have the Car element be deserialized as a Car object not a Vehicle object.

I can get everything a Vehicle[] and each element is a specific Vehicle type.


Solution

  • Put them all in the Vehicle Array and then just cast them using the instanceof

    if(a instanceof Car)
        a = (Car) a ;
    else if(a instanceof Truck)
        ...