[英]Is it possible to check at runtime whether or not a TYPE_USE annotation is present on an interface within a implements declaration?
考慮以下:
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!")
其他類似的方法包括:
請注意, AnnotatedType
具有子類型,例如AnnotatedParameterizedType
。 后一個接口讓我們獲得類型參數上存在的任何注釋:
要知道AnnotatedType
是否是子類型的實例,需要instanceof
測試(除非您已經確定)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.