Search code examples
javareflectionannotation-processing

How to check a methods parameter type in an Annotation Processor?


With pure reflection this would be easy, but the annotation processor world seems to be different. How do I get from a TypeMirror returned by getParameterTypes() to String.class?

In my Annotation Processor I want to check if the currently visited method has exactly the form:

public boolean someName(String input)

I can check the primitive return type, but the String parameter makes problems:

private void processAnnotation(Element method, Messager msg) {
    final MyAnnotation ann = method.getAnnotation(MyAnnotation.class);
    if (method.getKind() != ElementKind.METHOD) {
      error("annotation only for methods", method);
    }
    Set<Modifier> modifiers = method.getModifiers();
    if(!modifiers.contains(Modifier.PUBLIC)) {
      error("annotated Element must be public", method);
    }
    if(modifiers.contains(Modifier.STATIC)) {
      error("annotated Element must not be static", method);
    }
    ExecutableType emeth = (ExecutableType)method.asType();
    if(!emeth.getReturnType().getKind().equals(TypeKind.BOOLEAN)) {
      error("annotated Element must have return type boolean", method);
    }
    if(emeth.getParameterTypes().size() != 1) {
      error("annotated Element must have exactly one parameter", method);
    } else {
      TypeMirror param0 = emeth.getParameterTypes().get(0);
      // TODO: check if param.get(0) is String
    }
}

Solution

  • We can go through Elements.getTypeElement to retrieve a type during processing by its canonical name.

    Types    types = processingEnv.getTypeUtils();
    Elements elems = processingEnv.getElementUtils();
    
    TypeMirror param0 = m.getParameterTypes.get(0);
    TypeMirror string = elems.getTypeElement("java.lang.String").asType();
    
    boolean isSame = types.isSameType(param0, string);
    

    There isn't a way to get a "class" as such, because annotation processing runs on a partial compilation and we can't load the classes which are being compiled.