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?

Limnic
  • 1,596
  • 1
  • 13
  • 38
  • possible duplicate of [Code replacement with an annotation processor](http://stackoverflow.com/questions/13690272/code-replacement-with-an-annotation-processor) – nhaarman May 31 '15 at 19:25
  • Did you finally find a way to do it? – coolguy Feb 05 '16 at 06:57
  • 2
    @coolguy 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) – Limnic Feb 05 '16 at 12:08

1 Answers1

0

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

xcesco
  • 4,118
  • 3
  • 26
  • 53