[英]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.