A Java API to generate Java source files

Daniel Fanjul picture Daniel Fanjul · Sep 23, 2008 · Viewed 54.3k times · Source

I'm looking for a framework to generate Java source files.

Something like the following API:

X clazz = Something.createClass("package name", "class name");
clazz.addSuperInterface("interface name");
clazz.addMethod("method name", returnType, argumentTypes, ...);

File targetDir = ...;
clazz.generate(targetDir);

Then, a java source file should be found in a sub-directory of the target directory.

Does anyone know such a framework?


EDIT:

  1. I really need the source files.
  2. I also would like to fill out the code of the methods.
  3. I'm looking for a high-level abstraction, not direct bytecode manipulation/generation.
  4. I also need the "structure of the class" in a tree of objects.
  5. The problem domain is general: to generate a large amount of very different classes, without a "common structure".

SOLUTIONS
I have posted 2 answers based in your answers... with CodeModel and with Eclipse JDT.

I have used CodeModel in my solution, :-)

Answer

skaffman picture skaffman · Sep 23, 2008

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 http://codemodel.java.net/