简体   繁体   中英

Find Method Arguments of annotated Method using Java Annotation Processor?

I have the following annotation:

@Target(ElementType.METHOD)
public @interface MyAnn {
}

and a method annotated with @MyAnn :

  @MyAnn
  Object myMehtod(Object x) {
  ...
  }

Using a Java annotation processor I get the annotated element as:

Element annotatedElement // = myMehtod 
  1. How do I get the return type of this method?
  2. How do I get the arguments of this method?
  3. How do I get the name of the arguments of this method?

Here is my solution:

ExecutableType executableType = (ExecutableType)annotatedElement.asType();
List<? extends TypeMirror> parameters = executableType.getParameterTypes();
TypeMirror param1 = parameters.get(0);
DeclaredType declaredType = (DeclaredType)param1;
List<? extends AnnotationMirror> anns = ((TypeElement)declaredType.asElement()).getAnnotationMirrors( );
ExecutableElement method = ...

You can get the return type of the method with

TypeMirror returnType = mehod.asType()

You can get the arguments of the method with

List<? extends VariableElement> parameters = method.getParameters();

You can get the name of the parameter with

parameters.forEach(p -> {
            String name = p.getSimpleName().toString();
            TypeMirror type = p.asType();
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM