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?

3
  • Does processingEnv.getElementUtils().getTypeElement("java.util.List") return a sensible type? Commented Dec 26, 2019 at 23:41
  • Also, could you try using List.class.getCanonicalName() and Collection.class.getCanonicalName() instead of "java.util.List" and "java.util.Collection"? Commented Dec 26, 2019 at 23:48
  • 1
    You're testing if the generic List<E> is assignable to the generic Collection<E>, which is false. In your case, I assume you want to test the raw types—see Types#erasure(TypeMirror). Commented Dec 27, 2019 at 0:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.