Reading bytecode from an AnnotationProcessor [duplicate]
-
20-09-2019 - |
Question
Possible Duplicate:
Plugging in to Java compilers
Edit - this appears to be a dupe of Plugging in to Java compilers
I would like to implement an AnnotationProcessor
for use with the apt
tool that will be invoked after compiling a class to bytecode, that can read and modify the bytecode.
The reason for doing this is that I want to translate annotated methods to another language and replace the java methods with stubs that invoke the translated versions.
However the AnnotationProcessorEnvironment
interface only provides methods to generate new classes, not to read back a class file that was generated in a previous round.
The instrumentation API does something similar to what I want, but only at run-time. I am looking for a way to do this at compile time.
Solution
- Related: Plugging in to Java compilers
I had a look when I wanted to do some manipulation in the compiler, but ended up using a post-processor.
You can manipulate the abstract syntax tree (AST) using the APT, but only with compiler-specific hacks. If you want a sample of how that's done, Project Lombok does it with the Sun javac
and Eclipse compilers. At present, there doesn't seem to be a better method.