Hi All,
I was looking for a simple way to generate Java code. I found a utility called CodeModel which is part of JAXB. It works fine but it's documentation is very problematic. I was looking for a simple code sample and I couldn't find it.
After some try and error, I managed to conduct the following code sample:
import java.io.File;
import com.sun.codemodel.*;
public class MyTest {
public static void main(String[] args) throws Exception {
JCodeModel codeModel = new JCodeModel();
JPackage cl = codeModel.rootPackage();
cl = cl.subPackage("mypackage");
JDefinedClass def = cl._class("MyClass");
JMethod method = def.method(3, String.class, "myMethod");
method.param(String.class, "a");
method.param(String.class, "b");
method.param(Integer.class, "c");
JBlock bl = method.body();
bl._return();
def.field(1, Integer.class, "myInteger");
codeModel.build(new File("C:/MyTestDir"));
}
}
The result of this is:
package mypackage;
public class MyClass {
public Integer myInteger;
public protected String myMethod(String a, String b, Integer c) {
return ;
}
}
Enjoy,
Daniel