newlogic:
次のことを考えてみましょう:
class A implements @X B, C, @X D {}
それが実装宣言が実装するインタフェースのそれぞれに@ Xが含まれているかどうかを実行時に取得することは可能ですか?
したがって、上記の例では、Bのための答えがノーCおよびDはいため、イエスです。
もしそうであれば、どのように私はこれを実現するのでしょうか?
なスロー:
はい、これがで可能ですClass#getAnnotatedInterfaces()
。
配列を返し
AnnotatedType
、この表されるエンティティのスーパー指定するタイプの使用を表すオブジェクトClass
オブジェクト。(使用タイプのはFoo
区別される「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
。後者のインタフェースみましょう1は、型引数のいずれかの注釈が存在し得ることを:
かどうかを知るためにAnnotatedType
サブタイプのインスタンスであることが必要ですinstanceof
(すでに確かに知っていない限り)テストを。