Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java Code Generation - CodeModel

807580Feb 4 2009 — edited Aug 3 2010
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 31 2010
Added on Feb 4 2009
5 comments
2,799 views