Search code examples
javaannotations

How to get return type of annotated method in annotation processor?


I am learning to write custom annotations. I have a simple annotation that needs to verify if the return type of a method matches return type specified in the annotation. Below is the code.

Annotation code:

@Target(ElementType.METHOD)
public @interface ReturnCheck {
    String value() default "void";
}

Annotation processor:

@SupportedAnnotationTypes("com.rajesh.customannotations.ReturnCheck")
public class ReturnCheckProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        for ( Element element : roundEnv.getElementsAnnotatedWith(ReturnCheck.class) ) {

            //Get return type of the method


        }

        return false;
    }

}

I want to get the return type of the annotated method so that I can compare it with the value specified in the annotation.

How can I get the return type of the method ?


Solution

  • Here is what you need:

    if (element.getKind() == ElementKind.METHOD) {
        TypeMirror returnType = ((ExecutableElement) element).getReturnType();
        // use returnType for stuff ...
    }
    

    Explanation:

    You can check the ElementKind in order to dispatch on its concrete type. This is the recommended way to do it instead of instanceof. After that you know its an ExecutableElement and can cast it to one.

    See ExecutableElement, and Element for more details.