简体   繁体   English

Java注释-如何检查带注释的元素是否实现了接口?

[英]Java Annotations - How can you check if an annotated element implements an interface?

Suppose that I have a class, and in this class, I have an instance of some object that implements MyInterface, which is annotated by @MyAnnotation 假设我有一个类,并且在这个类中,我有一个实现MyInterface的对象的实例,该实例由@MyAnnotation注释

In my annotation compiler, I get a list of Elements that are annotated by @MyAnnotation 在我的注释编译器中,我获得了由@MyAnnotation注释的Elements的列表。

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(MyAnnotation.class);

    for (Element element : elements) {
        // How can I check if the class that `element` represents, implements my interface?
    }
    ...
}

I understand that I could have a list of classes that implement that interface, and then check if the class that the element represents is one of those classes, but obviously this solution isn't ideal 我了解我可以列出实现该接口的类,然后检查该元素表示的类是否为这些类之一,但显然此解决方案并不理想

Does anyone know if this is possible? 有人知道这是否可能吗?

Found the answer: 找到了答案:

public static boolean isInstanceOf(Types types, Elements elements, String class1, String class2) {
    Element element1 = elements.getTypeElement(class1);
    Element element2 = elements.getTypeElement(class2);

    if (element1 == null || element2 == null) {
        return false;
    }

    return types.isAssignable(element1.asType(), element2.asType());
}

Any class who is define as an implementation of your interface, can be checked using instanceof . 可以使用instanceof检查任何定义为接口实现的类。

if (element instanceof MyInterface) {
    // your code here!
}

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

相关问题 Java Annotations Processor:检查TypeMirror是否实现特定接口 - Java Annotations Processor: Check if TypeMirror implements specific interface 实现接口的 Java class 可以自动继承注释吗? - Can a Java class which implements an interface inherit the annotations automatically? 如何在Java中检查对象是否实现了特定的接口,而不是该接口的后代 - How to check if object implements particular interface, but not the descendants of this interface, in Java 您可以将对象强制转换为实现接口的对象吗? (JAVA) - Can you cast an object to one that implements an interface? (JAVA) 如果COM对象实现了接口,如何使用JIntegra在Java中进行检查? - How to check in Java using JIntegra if COM object implements an interface? 如何实例化在Java中实现Java接口的JRuby类 - How can I instantiate a JRuby class that implements a Java interface in Java 如何确定Java泛型是否实现特定接口? - How can I determine if Java generic implements a particular interface? 如何指定对象在Java中实现接口? - How can I specify that an object implements an interface in Java? 如何获得在Java中实现特定接口的正确枚举? - How can I get the proper enum that implements a particular interface in Java? 如何检查类类型并查看其是否实现了接口 - How to check for a class type and see if it implements an interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM