user915745
user915745

Reputation: 163

Dynamically generating java class from a java program

At the build(compile) time of my project I need to do code-generation for a java class. The generated java class is a java bean class with a set of getters and setters. At the build time I am getting the name of the class and names of variables. So what I need to do is dynamically generate the java bean from the information which I have.

eg. At the compile time I am getting following data.

class-name=Test
variable-name=aaa

So the generate class should look like following.

public class Test {
   public String aaa;
   public void setVar(String str) {
      this.aaa = str; 
   }
   public String getVar(){
      return this.aaa;
   }
}

When I searched for a tool that I can use, I found Arch4j [1] interesting but the problem with that is it is not compatible with Apache 2.0 license. I am looking for a project/tool that is compatible with Apache 2.0 license.

I would appreciate if someone can give me some insight on how I can do this.

[1] - http://arch4j.sourceforge.net/components/generator/index.html

Upvotes: 5

Views: 18541

Answers (4)

Ali
Ali

Reputation: 12684

Odd suggestion, but it seems like you want to generate beans. Why not use something like apache common's DynaBean? They allow you to create beans at run time. Here is an example of using DynaBean.

Of course this is at run time and not compile time. For compile time, I would recommend using an ant task to compile your source and add a dependency for compile on generation of your classes. You can handle the classes generation by writing a small java application that uses velocity as the java class template's engine.

So your ant task on compile first calls a small java program that generates the java class files using velocity template (delete the old files in ant if needed). Then compile as normal.

Upvotes: 1

OscarRyz
OscarRyz

Reputation: 199324

Take a look at javax.tools package. You can create and load a dynamically generated class only with that package.

Just bear in mind you need the JDK available and that's not re-distributable so your customer would need to downloaded it separately ( just like you do in any IDE today )

http://download.oracle.com/javase/6/docs/api/javax/tools/package-summary.html

For instance, you can invoke the java compiler programatically with:

http://download.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html

And you can load it with URLClassLoader

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692121

Why not just generate the .java file during your build, using a custom ant task or Maven plugin? This seems like a rather easy task which doesn't need any complex library. You could even use a template file with placeholders for the class name and the field name, and generate the real .java file using a replace task.

Upvotes: 6

Related Questions