Search code examples
javaannotationsjvmannotation-processing

Check class hierarchy at compile on an annotation processor


I'm writing an annotation processor to perform the following check at compile time:

  • There's an interface E
  • There's an annotation @Apply which is used to annotate methods.
  • Methods annotated with @Apply should be called apply and take only one parameter of a class implementing E

I've gotten so far as to identify all annotated methods called apply and extract the name of the class they take as parameter. So I'm left with :

 Element method  // this is the Element that represents the `apply` method
 TypeMirror mirror //method's TypeMirror
 String paramClass // the parameter's class Name.

The question is: How, if at all, can I get out of these the class hierarchy representation of the parameter, so I can check it implements E. Can't use ClassLoader.loadClass since the class doesn't exist already, but I just need the class hierarchy.


Solution

  • There happens to be an easy way using the javax.lang.model.util.Types.isSubtype() method:

     TypeMirror parameterTypes = mirror.getParameterTypes();
     TypeMirror typeOfE = processingEnv.getElementUtils().getTypeElement(E.class.getName()).asType();
     boolean isSubTypeOfE = processingEnv.getTypeUtils().isSubtype(parameterType, eventType)
    

    With that I can check if the parameter class of the method represented by mirror is a subtype of the required type E