I experimented with code generation in the annotation handler.
Consider the following code snippet, which adds a constructor in which there is an instruction.
private void addRegister(ExecutableElement el) { MethodSpec builder = MethodSpec.constructorBuilder().addStatement("$T.register(this)", EventExecutor.class).build(); TypeSpec spec = TypeSpec.classBuilder(el.getEnclosingElement().getSimpleName().toString()).addOriginatingElement(el).addMethod(builder).build(); JavaFile file = JavaFile.builder(pEnv.getElementUtils().getPackageOf(el.getEnclosingElement()).getQualifiedName().toString(), spec).build(); pEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, file.toString()); }
Now that the given executable is named "bla" in the "Test" class, the result is this:
class Test { Test() { EventExecutor.register(this); } }
However, this class already exists, and I want to add a constructor to the existing code, and not create this new class here.
Existing Code:
public class Test { @Event public void bla(TestEvent event) { } }
Can I do it?
java annotation-processing javapoet
Limnic
source share