Attach javapoet / javawriter to an existing class

I've been experimenting with code generation in annotation processors

Consider the following code and add a constructor that contains the statement

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 an executable element named "BLA" is given in the "test" class, the results are as follows:

class Test {
   test() {
     EventExecutor.register(this);
   }
}

But this class already exists. I want to append the constructor to the existing code instead of creating this new class here

Existing code:

public class Test {

    @Event
    public void bla(TestEvent event) {

    }
}

Can I do this?

Solution

No, the annotation processor cannot modify existing code They can only generate new code After reading this question, the problem is the same

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>