Javapoet/JavaWriter append to existing class
Asked Answered
D

1

7

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?

Dollarbird answered 27/4, 2015 at 20:47 Comment(3)
possible duplicate of Code replacement with an annotation processorFayola
Did you finally find a way to do it?Heterogenetic
@Heterogenetic Instead of trying to append to existing classes, my goal could also be achieved by using ASM to modify the runtime and also using aspect oriented programming using AspectJ. However I realized, if I were to use this approach now, it would be better if I just generate a new temporary class and append contents of that class manually to an existing file. (No magic)Dollarbird
C
0

No, Annotation processors cannot modify existing code. They can only generate new code. Read this question, the problem is the same.

Chauffer answered 9/7, 2018 at 0:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.