Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify the AST before the java compiler compiling the AST to class file

Tags:

java

javac

I want to add something(e.g: add method or field) before the source code is compiled to class file. But I don't know how to do it. Is there any way that I can do that?

I know one open source project Lombok, it can add setters and getters method to a class automatically and the IDE(eclipse) can find the new-added method right now. So someone can tell me how did it achieve?

like image 293
Tony Avatar asked Sep 02 '25 05:09

Tony


1 Answers

The source code for lombok is on github. Afaik it uses the internal api of javac annotation processing feature. Annotation processors are only supposed to be able to create new files, not modify the currently compiled one. By typecasting, patching the classloader and overriding some methods, lombok is able to modify the abstract syntax tree of the java file currently compiling and add methods or source code. It works, but I would consider it a hack and not rely to much on it.

If you want to modify the created classfiles, a bytecode rewriting framework like cglib or asm is the cleaner solution in my opinion.

like image 105
Jörn Horstmann Avatar answered Sep 04 '25 21:09

Jörn Horstmann