2

In my Java application I have a class Foo

class Foo {
  String field1;
  String field2;
}

I would like to have some generated code which uses reflection on the fields in this class (Imaginary template language)

#for each Field $f in Foo.class.getDeclaredFields()
  #writeFile $f.java
    public @interface $f {
    }

The end goal is to have Field1.java and Field2.java with just a simple @interface definition inside each.

Is there a templating language available which could do this generation as part of a Maven build process?

The closest I have been able to find is JET, but this project seems more geared towards generating Java source to be available at runtime, not at compile time. In theory I could probably make this work using AntRun along with several Javac and Java tasks, but it would be cumbersome.

The actual use case which I need this for is generating BindingAnnotations for Google Guice (which will be used in GWT source, so they must exist as .java files at compile time).

Community
  • 1
  • 1
idle
  • 1,117
  • 9
  • 17

2 Answers2

0

Take a look at Acceleo it is based on XSL Templates to generate source code . I used it with EMF to generate source code from a Data Model designed by the user.

Mehdi
  • 1,494
  • 5
  • 33
  • 53
0

I would suggest two options here:

  1. Apache Velocity: it provides a template language looking close to what you describe. Look into it here. You could probably be interested by their engine.

  2. GWTP seems to do something similar to what you are wanting to do. It looks likes they are using annotation processor to perform their code generation. Here is a processor example and their project home is here.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • I looked into Velocity a bit, but I couldn't figure out how to get reflective information from my class from within the template (the field names) when run from a maven build. GWTP looks like a very interesting project, and I will have to check into it more. It looks like it is possible, though challenging, to get the generator to run from a Maven build (http://groups.google.com/group/gwt-platform/browse_thread/thread/cad03cb1a7b98c9e/d060ebd4c26b4534) – idle Apr 24 '12 at 14:52
  • I worry that I might run into issues that the generated Field1.java file will be linked statically by other sources to compile (ie a binding in a guice module), so generation of the sources must occur before normal compilation. Do you know if GWTP could do this? – idle Apr 24 '12 at 14:54
  • @user460976 I don't think they can. I believe that the annotation processing occurs just before compilation and therefore it works, but as long as you haven't compiled the code, the generated code is not present either. The first time you want to use that, you need to annotate the code and then compile it so that the generated files are created. – Guillaume Polet Apr 24 '12 at 14:57