Plugging in to Java compilers

前端 未结 2 1028
时光说笑
时光说笑 2020-12-06 19:07

I have a post-compilation step that manipulates the Java bytecode of generated classes. I\'d like to make life as painless as possible for library consumers, so I\'m looking

相关标签:
2条回答
  • 2020-12-06 19:50

    The Groovy compiler is the only bytecode compiler which allows to hook into the compilation process (example: Generate bytecode to support the Singleton pattern)

    The Annotation Processing API is not meant to change the code. As you have already found out, all you can do is install a classloader, examine the bytecode at runtime and manipulate it. It's braindead but it works. This follows the general "we're afraid that a developer could try something stupid" theme which you will find throughout Java. There is no way to extend javac. The relevant classes are either private, final or will change with the next version of Java.

    Another option is to write annotated Java, for example you write a class "ExampleTpl.java". Then, you use a precompiler which expands the annotations in that file to get "Example.java". In the rest of the code, you use Example and ignore ExampleTpl.

    For Eclipse, there is a bug report to automate this step. I'm not aware of any other work in this area.

    0 讨论(0)
  • 2020-12-06 19:51

    It can be done.

    Take a look at my blog post Roman Numerals, in our Java where an annotation processor is used to rewrite code. Limitation being that it works with Sun's javac only.

    0 讨论(0)
提交回复
热议问题