• Post Reply Bookmark Topic Watch Topic
  • New Topic

Create and Load Classes dynamically  RSS feed

 
Nikhil Francis
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a requirement in my project.
I have a xml template file which holds information like class name, and its properties with datatype.
My requirement is to dynamically create a class from this XML so that I can create instance for the same.

Please help me ...
 
Jean-Francois Briere
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a DOM parser to parse the XML file and get all the information required.
Then you could create the corresponding .java file (as a text file) with the information obtained.
Then you could use the com.sun.tools.javac.Main class to compile this newly created .java file into a .class file.
Then you could use the Class.forName() method to load the class (of course the root folder of the generated .class file must be in the class path).

Regards
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could look at XDoclet for code generation, it's a little tricky to get started but very versatile. I haven't used it, but you may be able to build your classes using bcel.

Dave
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you need to create the class dynamically? Is the format completely unknown beforehand? A library like Jakarta Commons Digester can handle a good deal of variety in the XML it digests.

One library for creating classes on the fly which I found easy and powerful to work with is Javassist.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!