Reputation: 953
I'd like to generate Java code which is based on existing Java code.
Here comes an example:
@A
class A {
@A
a;
@A
b;
c;
}
@A
class B {
a;
@A
b;
c;
}
A.java, B.java -(code transformer)-> A.java, B.java
The transformed code should look like this:
class A {
a;
b;
}
class B {
b;
}
As you can see, all the stuff (classes, fields, methods, ...) annotated with a custom annotation should be part of the resulting code. All the other stuff is dissmissed.
Note: The implementations of the particular methods should be part of the resulting code. All used types should be imported, ...
Any hints how to do it with this project: https://today.java.net/pub/a/today/2008/04/10/source-code-analysis-using-java-6-compiler-apis.html#accessing-the-abstract-syntax-tree-the-compiler-tree-api
?
Best regards
Upvotes: 2
Views: 923
Reputation: 126
JavaForger parses existing source code and generates new code based on templates. The template below will generate the code you requested.
class ${class.name} {
<#list fields as field>
<#if field.annotations?seq_contains("A")>
${field};
</#if>
</#list>
}
The project can be found on github: https://github.com/daanvdh/JavaForger
A list of parsed variables can be found here: https://github.com/daanvdh/JavaForger/blob/master/TemplateVariables.md
Upvotes: 0
Reputation: 5874
Java 6.0 has an Annotation Processing API which can be invoked via the compiler. This API allows you to create customized Annotation Processors which can traverse the Java Mirror trees representing your annotated classes. Though it's complicated, this can be leveraged to process and generate new source files.
I've used this extensively for source-file generation (Java-to-Java and Java-to-Python), and have been very impressed with it.
Here are a few links which might help you get started:
Upvotes: 1
Reputation: 1
you can simply write and compile a java application that reads the uncompiled class .java as text and choose needed code according to @ or any special characters in comments that does not affect the code, then re-write the transformed code to another file.java then compile it.
Upvotes: 0
Reputation: 26868
The standard way to do something like this is to parse the program to some AST (using, for example, the API you mentioned), then modify the AST in any way you wish - e.g., filtering out aspects without some annotation - and finally, creating some visitor which can print the AST back to source code form. This way should work, though you lose source formatting. Also, creating the printing-back-source-code visitor is quite a chore.
Alternatively, you can use existing libraries for Java source transformation (which probably work in the same way as the above), for example Spoon. Specifically, here's a Spoon filter which only matches elements with a given annotation - exactly what you're looking for.
Upvotes: 1