Dilip
Dilip

Reputation: 959

JAXB - Dynamic Object Creation from XML Document

I have list of XML files for the user to send the request. By runtime only i comes know what type of object JAXB is going to create. For example if user sends the request like

<books>
<name>Java</name>
</books>

Then i wants create a Book object. If the user sends the request like

<Customer>
<id>1</id>
</Customer> 

Then i wants to create a Customer object . But when i unmarshalling the XML using JAXB i need to specify the object type like

Person person= (Person) jaxbUnmarshaller.unmarshal(file); 

Is this anyway to create those objects dynamically?

Please help me.

Upvotes: 1

Views: 888

Answers (1)

bdoughan
bdoughan

Reputation: 148977

Without the explicit cast, with the code below object could hold an instance of Book or Person based on the content of the XML file.

JAXBContext jc = JAXBContext.newInstance(Book.class, Person.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Object object = unmarshaller.unmarshal(file) ;

Upvotes: 1

Related Questions