I have been experimenting with code generation in an annotation processor.
Consider the following piece of code that adds a constructor that has a statement in it.
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, when given an executable element named "bla" in class "Test" the result is this:
class Test {
Test() {
EventExecutor.register(this);
}
}
However this class already exists and I want to append the constructor to the existing code rather than create this fresh class here.
Existing code:
public class Test {
@Event
public void bla(TestEvent event) {
}
}
Can I do this?