views:

65

answers:

6

Hello,

Is it possible to create a class dynamically by reading an xml file ( in java preferably) ? if yes, please provide pointers on how to do it.

In the process of development, we have come up with a class that has 5 attributes, all these attributes correspond to an entry in the xml file, now if the user adds/modifies the xml entry the object corresponding to it must change automatically, one approach would be generate the source code, before compile time.Is there any other way ?

Is there any common pattern to model such changes in the system ?

Thanks,

A: 

The process usually works the other way around (ie. defining a class with those attributes, and serializing an instance of the class to XML)

If you really need that sort of flexibility, a scripting language would save you a lot of trouble.

Pierreten
+4  A: 

If you have an XML Schema for your XML there are a number of kits for this. Start with JAX-B.

bmargulies
Thanks for the information, I am going through it. Just before I get through the entire doc, I had a quick question : At present, I already have a static class declaration that is used across the module, what will JAX-B do for me ? will it replace the static compile time class with the one it generates at runtime ?Thanks
panzerschreck
You can either tell JAXB to generate a Java source file from an XSD, or the other way around, or you can mess around with @annotations until they converge.
bmargulies
A: 

I think JAX-B can provide functionality like that.

Lars Andren
A: 

If you're looking for byte code generation, have a look at cglib, it is the one used in Hibernate.

But maybe some annotations can also fulfill your requirement, just like Google Guice's dependency injection.

Kymair Wu
+1  A: 

If you stored your attributes in a HashMap then you could simply parse the XML and then set the attributes accordingly.

Romain Hippeau
A: 

Assuming you have a XML schema (xsd), you can feed that schema to JAXB's xjc command to generate Java classes. xjc is included with the Java 6 JDK.

Brice Busselman