Question

The getInterfaces() method of TypeElement only returns the interfaces directly implemented by the element. Is there an easy way to find if a given TypeElement implements a given interface indirectly?

That is say I have a TypeElement and I want to know if somewhere up the line it descends from a given interface.

Was it helpful?

Solution

I've never actually used any of this stuff, only reading about it.

I believe you can iterate over the returned types and use Types#isAssignable(TypeMirror t1, TypeMirror t2) to check if any of them are assignable to the interface you are looking for (in this context, a is assignable to b if a is b or b is a superinterface of a -- but for a full definition see JLS section 5.2). Something like:

public static boolean implementsInterface (TypeElement myTypeElement, TypeMirror desiredInterface) {
    for (TypeMirror t : myTypeElement.getInterfaces())
        if (processingEnv.getTypeUtils().isAssignable(t, desiredInterface))
            return true;
    return false;
}

Or, even better, directly, like this (maybe):

public static boolean implementsInterface (TypeElement myTypeElement, TypeMirror desiredInterface) {
    return processingEnv.getTypeUtils().isAssignable(myTypeElement.asType(), desiredInterface);
}

Where processingEnv is a ProcessingEnvironment (see ThePyroEagle's comment below).

Sorry, I can't test this, and again, I'm just basing off of documentation. You should test these yourself.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top