Is it possible to control the JVM bytecode at compile time?

Can I use a bytecode manipulation library like ASM at compile time?

In particular, I would like to use the Java Annotation Processing API to implement complex patterns in annotated classes. Implementing a comment handler is simple enough, but it seems that the .class files do not yet exist when Processor is running. Is there another way?

+4
source share
3 answers

This should be possible, as the following project does this: Project Lombok

also:

Java 8 introduced a new mechanism for writing plugins for the Java compiler (javac). The compiler plugin allows you to add new phases to javac without making changes to its code base. New behavior can be encapsulated in the plugin and distributed to other people. For example, javac plugins can be used to do the following:

• Add additional compile time checks

• Add code conversions

• Perform individual source code analysis

+1
source

You might be interested in Javassist ( http://www.jboss.org/javassist ), which can improve and save classes as a stage after compilation.

This article describes how to save advanced classes: http://java.dzone.com/articles/implementing-build-time

in particular, once you have changed the class, you can do something like this:

  compiledClass.writeFile("/tmp/modifiedClassesFolder"); 
0
source

You should use CGLib instead. With CGLib, you can add proxies using method hooks and have a hook that implements your boilerplate code. Another option is to look at the Javassist. With Javassist, you literally create a new subclass using the actual text (in lines), and javassist compiles it into byte code.

-1
source