views:

33

answers:

3

I want to create a class dynamically at run time by reading field names and its types from an xml file.For example my xml file looks like this:

<person>
   <name type="String">abc</name>
   <age type="Integer">30</age>
</person>

I also want to have getter and setters methods for each field.

Any examples or best approaches available for this?

+1  A: 

Take a look at XStream, it is extremely easy to serialize to/from XML.

matt b
I think he wants to be able to construct Java objects even if his code has never heard of the originally serialized classes before.
Pointy
+1  A: 

This is technically possible, but (unless someone can point out an existing solution) it would be a lot of work. (You can do a lot of clever things by generating source code and compiling it at runtime ... for example.)

But to be honest, this is probably not a useful thing to do. Once you've loaded your XML object as an instance of a brand new Java class, you'll have great difficulty using it. For a start, your existing statically compiled application will only be able to access the fields and methods of the new class reflectively.

IMO, you'd be better of loading the XML into generic Map objects or Properties objects. Or, just use a DOM created by an off-the-shelf XML parser.

Alternatively, get hold of a DTD, XSD, or some other kind of "schema" for the XML and generate Java classes from that. Then can write and statically compile your application to call those classes.

Stephen C
A: 

Java is not a dynamic language, so you cannot create classes dynamically, but the term 'create' is not well defined in your question.

If you mean instantiate and initialize, that can be done very easily through serialization with libraries like:

  • jaxb.dev.java.net/
  • www.castor.org/
  • jibx.sourceforge.net/
  • xstream.codehaus.org/

etc.

If you mean you want to actually create a class file within the JVM at runtime, you might want to look at more dynamic langauges capable of running in a JVM like Groovy, or JRuby, etc. Groovy has some pretty cool dynamic capabilities.

hisdrewness