3

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?

2 Answers 2

8

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( );
Sign up to request clarification or add additional context in comments.

3 Comments

ExecutableType executableType = (ExecutableType)annotatedElement.asType(); is causing me compiler errors. Types are not compatible.
@Samuel That means the thing with the annotation is not a method. Perhaps you've accidentally annotated the return type instead? That would explain the problems you encountered.
you are supposed to cast the element, not the type: (ExecutableElement)annotatedElement
5
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();
   });

2 Comments

Hi, I always get "arg0" as name for my parameter. What am I missing ?
One has to add -parameters option to javac when compiling the classes to get parameters names added to metadata for reflection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.