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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With