I am trying to generate code by reading annotated method like
@MyAnnotation
public static int generatorMethod(@SomeOtherAnnotation Boolean someArg)
I would like to copy the list of arguments as they are in the generated code
As shown below:
public class MyGeneratedClass{
public int myGeneratedMethod(@SomeOtherAnnotation Boolean someArg) {
//method body
}
}
But when I try to read annotated methods from annotationProcessor class
for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
messager.printMessage(
Diagnostic.Kind.NOTE, String.format("Annotated Element as string: %s",
annotatedElement.toString()));
}
It prints the value as
Annotated Element as string: generatorMethod(java.lang.Boolean)
Which has no reference to argument's annotation which I could use to create ParameterSpec.
Is there a way to read argument's annotation?
(This doesn't seem to be about JavaPoet at all, which is for writing details out to a new java file, not reading details of the type.)
The Element.toString() method really only makes sense for debugging purposes - different implementations of the APT api (Eclipse's JDT for example) return different values. It isn't an effective way to print the full description of the method, which also would need to include the return type, whether it is final/abstract/native/public/private/etc.
Instead, you read the details about the method from the Element (which is an ExecutableElement) instance. If you are trying to create the method with JavaPoet, you should use a MethodSpec builder, and pass each detail from the Element into the builder to create the method spec.
As mentioned above, since this is a method, it is an
ExecutableElement
, which has specific methods to read parameters (and type parameters), as well as check if the method as a varargs param, etc.Each parameter then will be a
VariableElement
, which also extends fromElement
, and so you can read the annotations present on it.