简体   繁体   English

如何判断TypeElement是否间接实现了接口

[英]How to tell if a TypeElement indirectly implements an interface

The getInterfaces() method of TypeElement only returns the interfaces directly implemented by the element. TypeElementgetInterfaces()方法仅返回由元素直接实现的接口。 Is there an easy way to find if a given TypeElement implements a given interface indirectly? 是否有一种简单的方法来查找给定的TypeElement是否间接实现给定的接口?

That is say I have a TypeElement and I want to know if somewhere up the line it descends from a given interface. 也就是说我有一个TypeElement ,我想知道它是否从某个给定的接口下行的某个地方。

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 ). 我相信你可以迭代返回的类型并使用Types#isAssignable(TypeMirror t1, TypeMirror t2)来检查它们中的任何一个是否可以分配给你正在寻找的接口(在这种情况下,如果a是b,则可以分配给b)或b是a的超接口 - 但是对于完整定义,请参阅JLS第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). 其中processingEnvProcessingEnvironment (请参阅下面的ThePyroEagle的评论)。

Sorry, I can't test this, and again, I'm just basing off of documentation . 对不起,我无法测试这个,而且,我只是基于文档 You should test these yourself. 你应该自己测试一下。

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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