考虑以下内容:
class A implements @X B, C, @X D {}
是否可以在运行时检索implements声明是否在每个实现接口上都包含@X?
所以在上面的例子中,对于B,答案是肯定的,对于C,答案是否定的,对于D,答案是必然的。
如果是,我将如何实现这一点?
是的,这在Class#getAnnotatedInterfaces()
中是可能的。
返回一个
AnnotatedType
对象数组,该数组表示使用类型来指定由该Class
对象表示的实体的超接口。(Foo
类型的使用来指定"…implements Foo"中的超接口与Foo
类型的声明不同。([…]
例如:
package com.example;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
public class Main {
public static void main(String[] args) {
for (AnnotatedType type : A.class.getAnnotatedInterfaces()) {
System.out.println(type.getType());
for (Annotation annotation : type.getAnnotations()) {
System.out.println("t" + annotation);
}
System.out.println();
}
}
@Retention(RUNTIME)
@Target(TYPE_USE)
@interface X {
String value();
}
interface B {}
interface C {}
interface D {}
static class A implements @X("Hello, ") B, C, @X("World!") D {}
}
输出:
interface com.example.Main$B
@com.example.Main$X("Hello, ")
interface com.example.Main$C
interface com.example.Main$D
@com.example.Main$X("World!")
其他类似的方法包括:
Class#getAnnotatedSuperclass()
Method#getAnnotatedReturnType()
Parameter#getAnnotatedType()
请注意,AnnotatedType
具有AnnotatedParameterizedType
等亚型。后一个接口让我们获得类型参数上的任何注释:
AnnotatedParameterizedType#getAnnotatedActualTypeArguments()
要知道AnnotatedType
是否是子类型的实例,需要进行instanceof
测试(除非您已经确定(。