lundi 18 mai 2015

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(not(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);
      TypeMirror param0 = emeth.getParameterTypes().get(0);
      // TODO: check if param.get(0) is String
    }
}





Aucun commentaire:

Enregistrer un commentaire