Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 225
user915745 Avatar asked Aug 27 '11 18:08

user915745


2 Answers

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.

like image 171
JB Nizet Avatar answered Oct 23 '22 11:10

JB Nizet


JET from Eclipse can be used:

http://eclipse.org/articles/Article-JET/jet_tutorial1.html

It can be called by ant: http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jet.doc/references/ant/antTasks.xhtml

And I think from maven: http://mvnrepository.com/artifact/org.eclipse/jet/0.8.0-v20070605

like image 24
Ant Kutschera Avatar answered Oct 23 '22 10:10

Ant Kutschera