Java does not allow annotation processors to affect the source or bytecode of classes you have written, only generate new classes.
In Java 17, there is a clever way around this restriction though.
Lets say you want to make an annotation processor that adds a toJson
method to a class based on some automated set of rules.
@AutoToJson
public record BasicThing(String color, String size) {}
What you can do is generate an interface with a predictable name
interface BasicThingToJson {}
Make it "sealed", so that only the class you want to can implement it
interface BasicThingToJson permits BasicThing {} sealed
And then inside of the interface you can add a default method, in which it is safe to assume that the only possible class that implements the interface is the class you want to
interface BasicThingToJson permits BasicThing {
sealed default JSON toJson() {
// totally safe
= (BasicThing) this;
var self = new JsonObject();
var jsonObject .set("color", self.color());
jsonObject.set("size", self.size());
jsonObjectreturn jsonObject;
}
}
And then all your user has to do is
@AutoToJson
public record BasicThing(String color, String size) implements BasicThingToJson {}
And then boom, their class has been "enriched" in whatever way you want.
= new BasicThing("red", "small");
var basicThing = basicThing.toJson(); var json