Dynamically creating a Java class from a java program

At the time of building (compiling) my project, I need to create code for the java class. The generated java class is a java bean class with a set of getters and setters. During build I get the class name and variable names. So what I need to do is dynamically generate a java bean from the information I have.

eg. At compile time, I get the following data.

class-name=Test variable-name=aaa 

So, the generate class should look like this.

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

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

I would appreciate it if someone can give me some idea of ​​how I can do this.

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

+4
source share
4 answers

Why not just generate a .java file during build using the custom ant task or the Maven plugin? This seems like a fairly simple task that does not require a complex library. You can even use a placeholder template file for the class name and field name and generate a real .java file using the replace task.

+6
source

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

Just keep in mind that you need a JDK that is accessible and non-redistributable, so your client will need to download it separately (as with any IDE today)

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

For example, you can program a java compiler programmatically with

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

And you can load it using URLClassLoader

+1
source

An odd sentence, but it looks like you want to generate beans. Why not use something similar to Apache common DynaBean? They allow you to create beans at runtime. The following is an example of using DynaBean .

Of course, this is at runtime, not at compile time. At compile time, I would recommend using the ant task to compile your source and add a dependency to compile when generating your classes. You can handle class generations by writing a small Java application that uses velocity as the mechanism for a java class template.

So, your ant task, when compiling, first calls a small java program that generates java class files using a speed template (if necessary, delete the old files in ant). Then compile as usual.

+1
source

Source: https://habr.com/ru/post/1369307/


All Articles