0

I'm looking for a way to detect if a class is inherited from another class/interface in annotation processor. Since the annotation processor runs on the source code not runtime, there's no way to use reflation API, the only method I found is:

public class MyProcessor extends AbstractProcessor {

    @Override
    public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
        // Simple test
        processingEnv.getTypeUtils().isAssignable(
                processingEnv.getElementUtils().getTypeElement("java.util.List").asType(),
                processingEnv.getElementUtils().getTypeElement("java.util.Collection").asType()
        );

    }

}

But this method always returns false even though that List implements Collection. Any idea?

user1079877
  • 9,008
  • 4
  • 43
  • 54
  • Does `processingEnv.getElementUtils().getTypeElement("java.util.List")` return a sensible type? – Turing85 Dec 26 '19 at 23:41
  • Also, could you try using `List.class.getCanonicalName()` and `Collection.class.getCanonicalName()` instead of `"java.util.List"` and `"java.util.Collection"`? – Turing85 Dec 26 '19 at 23:48
  • 1
    You're testing if the _generic_ `List` is assignable to the _generic_ `Collection`, which is false. In your case, I assume you want to test the raw types—see [`Types#erasure(TypeMirror)`](https://docs.oracle.com/en/java/javase/13/docs/api/java.compiler/javax/lang/model/util/Types.html#erasure(javax.lang.model.type.TypeMirror)). – Slaw Dec 27 '19 at 00:05

1 Answers1

0

Thanks to Slaw's comment. This solution seems to work:

public class MyProcessor extends AbstractProcessor {

    @Override
    public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
        // Simple test
        processingEnv.getTypeUtils().isAssignable(
                        processingEnv.getTypeUtils().erasure(processingEnv.getElementUtils().getTypeElement("java.util.List").asType()),
                        processingEnv.getTypeUtils().erasure(processingEnv.getElementUtils().getTypeElement("java.util.Collection").asType())
        );

    }

}

You can find some more information about erasure and what it does in here: https://www.tutorialspoint.com/java_generics/java_generics_type_erasure.htm

user1079877
  • 9,008
  • 4
  • 43
  • 54