是否可以在运行时检查实现声明中的接口上是否存在TYPE_USE注释



考虑以下内容:

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测试(除非您已经确定(。

最新更新