简体   繁体   中英

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

In my annotation compiler, I get a list of Elements that are annotated by @MyAnnotation

@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 .

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

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