Accepted answer

sun provides an api called codemodel for generating java source files using an api. it's not the easiest thing to get information on, but it's there and it works extremely well.

the easiest way to get hold of it is as part of the jaxb 2 ri - the xjc schema-to-java generator uses codemodel to generate its java source, and it's part of the xjc jars. you can use it just for the codemodel.

grab it from


it really depends on what you are trying to do. code generation is a topic within itself. without a specific use-case, i suggest looking at velocity code generation/template library. also, if you are doing the code generation offline, i would suggest using something like argouml to go from uml diagram/object model to java code.


exemple : 1/

private jfieldvar generatedfield;


string classname = "class name";
        /* package name */
        jpackage jp = jcodemodel._package("package name ");
         /*  class name  */
        jdefinedclass jclass = jp._class(classname);
        /* add comment */
        jdoccomment jdoccomment = jclass.javadoc();
        jdoccomment.add("by automat d.i.t tools : " + new date() +" => " + classname);
        // génération des getter & setter & attribues

            // create attribue 
             this.generatedfield = jclass.field(jmod.private, integer.class) 
                     , "attribue name ");
             // getter
             jmethod getter = jclass.method(jmod.public, integer.class) 
                     , "attribue name ");
             // setter
             jmethod setter = jclass.method(jmod.public, integer.class) 
                     ,"attribue name ");
             // create setter paramétre 
             jvar setparam = setter.param(gettypedetailsforcodemodel(integer.class,"param name");
             // affectation  ( this.param = setparam ) 
             setter.body().assign(jexpr._this().ref(this.generatedfield), setparam); file("path c://javasrc//"));


here is a json-to-pojo project that looks interesting:


if you really need the source, i don't know of anything that generates source. you can however use asm or cglib to directly create the .class files.

you might be able to generate source from these, but i've only used them to generate bytecode.


i was doing it myself for a mock generator tool. it's a very simple task, even if you need to follow sun formatting guidelines. i bet you'd finish the code that does it faster then you found something that fits your goal on the internet.

you've basically outlined the api yourself. just fill it with the actual code now!


there is also stringtemplate. it is by the author of antlr and is quite powerful.


there is new project write-it-once. template based code generator. you write custom template using groovy, and generate file depending on java reflections. it's the simplest way to generate any file. you can make getters/settest/tostring by generating aspectj files, sql based on jpa annotations, inserts / updates based on enums and so on.

template example:

package ${};

public class ${cls.shortname}builder {

    public static ${}builder builder() {
        return new ${}builder();
<% for(field in cls.fields) {%>
    private ${} ${};
<% } %>
<% for(field in cls.fields) {%>
    public ${}builder ${}(${} ${}) {
        this.${} = ${};
        return this;
<% } %>
    public ${} build() {
        final ${} data = new ${}();
<% for(field in cls.fields) {%>
<% } %>
        return data;


i built something that looks very much like your theoretical dsl, called "sourcegen", but technically instead of a util project for an orm i wrote. the dsl looks like:

public void testtwomethods() {
    gclass gc = new gclass("");

    gmethod hello = gc.getmethod("hello");
    hello.arguments("string foo");
    hello.setbody("return 'hi' + foo;");

    gmethod goodbye = gc.getmethod("goodbye");
    goodbye.arguments("string foo");
    goodbye.setbody("return 'bye' + foo;");

    join.lines(new object[] {
        "public class foo {",
        "    public void hello(string foo) {",
        "        return \"hi\" + foo;",
        "    }",
        "    public void goodbye(string foo) {",
        "        return \"bye\" + foo;",
        "    }",
        "" }),

it also does some neat things like "auto-organize imports" any fqcns in parameters/return types, auto-pruning any old files that were not touched in this codegen run, correctly indenting inner classes, etc.

the idea is that generated code should be pretty to look at it, with no warnings (unused imports, etc.), just like the rest of your code. so much generated code is ugly to's horrible.

anyway, there is not a lot of docs, but i think the api is pretty simple/intuitive. the maven repo is here if anyone is interested.


don't know of a library, but a generic template engine might be all you need. there are a bunch of them, i personally have had good experience with freemarker


the eclipse jet project can be used to do source generation. i don't think it's api is exactly like the one you described, but every time i've heard of a project doing java source generation they've used jet or a homegrown tool.


another alternative is eclipse jdt's ast which is good if you need to rewrite arbitrary java source code rather than just generate source code. (and i believe it can be used independently from eclipse).


you can use roaster ( to do code generation.

here is an example:

javaclasssource source = roaster.create(javaclasssource.class);
source.addmethod().setname("testmethod").setprivate().setbody("return null;")

will display the following output:

public class myclass {
   private string testmethod() {
       return null;


solution found with eclipse jdt's ast
thanks, giles.

for example, with this code:

ast ast = ast.newast(ast.jls3);
compilationunit cu = ast.newcompilationunit();

packagedeclaration p1 = ast.newpackagedeclaration();

importdeclaration id = ast.newimportdeclaration();
id.setname(ast.newname(new string[] { "java", "util", "set" }));

typedeclaration td = ast.newtypedeclaration();
typeparameter tp = ast.newtypeparameter();

methoddeclaration md = ast.newmethoddeclaration();

block block = ast.newblock();

methodinvocation mi = ast.newmethodinvocation();

expressionstatement e = ast.newexpressionstatement(mi);


i can get this output:

package foo;
import java.util.set;
class foo<x> {
  void missing(){


solution found with codemodel
thanks, skaffman.

for example, with this code:

jcodemodel cm = new jcodemodel();
jdefinedclass dc = cm._class("");
jmethod m = dc.method(0, int.class, "foo");

file file = new file("./target/classes");

i can get this output:

package foo;
public class bar {
    int foo() {
        return  5;

Related Query

More Query from same tag