开发者

How to create java object by reflection by reading field names and types from an xml file?

I want to create a class dynamically at run time 开发者_StackOverflow社区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?


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


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.


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/
  • http://x-stream.github.io/

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜