Search code examples
javaeclipsecode-generationeclipse-jdt

Modify existing Java source programatically with Eclipse JDT ASTRewrite as a standalone application


I have an existing Java application containing source files that I'd like to modify programatically. I need to be able to do analysis on the source files and based on that analysis execute source transforms. I also need to be able to understand the relationships between different source files. I also would like to create this process as a standalone Java application.

Doing a little research I found the following tools: Code Model & Eclipse JDT. I'm sure there are others. I have excluded Code Model because it (to my knowledge) only allows the generation of new code and will not work with existing code.

The Eclipse JDT library seemed to fit all my needs. I was able to parse source files easily. I could configure binding such that information across types were preserved. The issue that I'm having now is getting the ASTRewrite feature to work. It seems (from the examples and documentation I've read) that it only works from within an eclipse plugin. When I try to use the rewriter I get the following error:

java.lang.IllegalArgumentException: This API can only be used if the AST is created from a compilation unit or class file 

So can I use the ASTRewrite feature from a standalone application or do I need to start looking at a different tool?


Solution

  • I did not complete the project but I put together a proof-of-concept tool that used:

    1. TattleTale for class dependencies.
    2. JavaParser for the analysis of the code.

    I was particularly impressed with JavaParser and TattleTale did what I needed it to do. JavaParser is certainly capable of changing the code on the fly.

    Obviously you will need both the jars and the sources as TattleTale works on the jars and JavaParser works with the source.