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("foo.Bar");
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