简体   繁体   中英

How to tell if a TypeElement indirectly implements an interface

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM