Javapoet / JavaWriter Adds to Existing Class

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?

+7
java annotation-processing javapoet
source share

No one has answered this question yet.

See similar questions:

17
Replacing code with the annotation handler
2
Can I add a method to a class from compile time annotation?

or similar:

1636
Java inner class and static nested class
904
What is the difference between canonical name, simple name and class name in Java Class?
896
Static Classes in Java
624
How to add text to an existing file in Java
one
Can a constructor use a builder
one
Work in progress documentation - Annotation
one
General JavaPoet Parameter
one
Should I create a builder for a class that has a large number of required attributes
one
How to recreate a class using JavaPoet?
0
Create a field as an anonymous class using JavaPoet

All Articles