Take the 2-minute tour ×

Is it possible to use a bytecode manipulation library like ASM at compile time?

Specifically, I'd like to use Java's annotation processing API to implement boilerplate-heavy methods on annotated classes. Implementing an annotation processor is straightforward enough, but it seems like the .class files don't yet exist when the Processor is run. Is there another way?

share|improve this question

3 Answers 3

It should be possible since the following project is doing it: Project Lombok


Java 8 will bring a new mechanism that allows you to write plug-ins for the Java compiler (javac). A compiler plug-in lets you add new phases to javac without making changes to its code base. New behavior can be encapsulated in a plug-in and distributed for other people to use. For example, javac plug-ins could be used to do the following:

• Add extra compile-time checks

• Add code transformations

• Perform customized analysis of source code

share|improve this answer

You might be interested in Javassist ( http://www.jboss.org/javassist ) which can enhance and save classes as a post-compilation step.

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

in particular, once you have altered a class, you can do something like this:

share|improve this answer

You should use CGLib instead. With CGLib you can add proxies with method interceptors and have the interceptor implement your boilerplate code. Another option is to look at Javassist. With Javassist you literally create a new subclass using actual text (in strings) and have javassist compile it into byte-code.

share|improve this answer
"Compile Time" -- don't those work at runtime? –  bmargulies Jan 28 '13 at 19:34

Your Answer


