How to determine if TypeElement indirectly implements an interface

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

This means that I have a TypeElement , and I want to know if it is somewhere up the line with which it is descending from this interface.

+4
source share
1 answer

I never used this material, only read about it.

I believe that you can Types#isAssignable(TypeMirror t1, TypeMirror t2) over returned types and use Types#isAssignable(TypeMirror t1, TypeMirror t2) to check if they can be assigned to the interface you are looking for (in this context, a is assigned to b if a is b or b , is the superinterface a, but for a complete definition see JLS section 5.2 ). Sort of:

 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 ProcessingEnvironment (see ThePyroEagle comment below).

Sorry, I can’t verify this, and again, I'm just based on the documentation . You must check them out yourself.

Hope this helps.

+4
source

Source: https://habr.com/ru/post/1496692/


All Articles