How to generate code dynamically with annotations at build time in Java?

The annotation processing tool has been integrated in javac since version 1.6 and is part of the JDK. So there is no need for external tools when using the Pluggable Annotation API. You can generate any code by analysing custom annotations or method/parameter/field/class declarations using the Mirror API.

The annotation processor API says you shouldn't change existing classes. Instead you should generate subclasses of existing classes and create extension methods on those subclasses.

It seems to be possible to change classes anyway (e.g. by using bytecode manipulation libraries) though that would in contrast to the specification and could lead to issues with other annotation processors and may not work with all compilers in the same way.


Have a look at Project Lombok. It generates code as you ask when you write:

public class MyClass {
  @Getter @Setter private String alias;
}

It also does a lot more if you need it. I know you asked for no external tools, but you would basically be recreating this.