注釈上記の注釈を取得する方法

鵬:

私は、メソッドにアノテーションを追加し、他の注釈がこの注釈です。私はこの方法により、上記の注釈を取得しようとすると、残念ながら、リターンは常にnullです。私は理由を知りたいですか?

これは私が定義された方法であり、

@ApiTest
public void add() {
}

これは私が定義された注釈です。

@ValueName("hello word")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiTest {

}
////////////////////////////////////////////////////////
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ValueName {
  String value() default "";
}

私は、get @ValueNameにしようとすると、結果は常にnullを返します。

Class<?> testApi = Class.forName("com.huawei.netty.TestApi");
    Method add = testApi.getMethod("add", null);
    ApiTest apiTest = add.getDeclaredAnnotation(ApiTest.class);
    ValueName valueName = apiTest.getClass().getDeclaredAnnotation(ValueName.class);
    if (valueName != null) {
      System.out.println(valueName.annotationType());
    }

しかし、この方法を得ることができます

Class<?> apiTest = Class.forName("com.huawei.netty.ApiTest");
    ValueName valueName = apiTest.getDeclaredAnnotation(ValueName.class);
    if (valueName != null) {
      System.out.println(valueName.value());
    }

これは、なぜ私が知っていることはできますか?

なスロー:

あなたは使うべきAnnotation#annotationType()ではなく、注釈インスタンスのクラスを取得しますObject#getClass()後者の方法は、あなたがそれだと思うクラスを返していません。次のことを試してみてください。

MetaAnnotation.java

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface MetaAnnotation {

    String value();

}

CustomAnnotation.java

@MetaAnnotation("Hello, World!")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomAnnotation {}

Main.java

@CustomAnnotation
public final class Main {

    public static void main(String[] args) {
        CustomAnnotation ca = Main.class.getAnnotation(CustomAnnotation.class);
        MetaAnnotation   ma = ca.annotationType().getAnnotation(MetaAnnotation.class);

        System.out.println("CustomAnnotation#getClass()       = " + ca.getClass());
        System.out.println("CustomAnnotation#annotationType() = " + ca.annotationType());
        System.out.println("MetaAnnotation#value()            = " + ma.value());
    }

}

私はOpenJDKの12.0.1を使用して、上記実行すると、私は次のような出力が得られます。

CustomAnnotation#getClass()       = class com.sun.proxy.$Proxy1
CustomAnnotation#annotationType() = interface CustomAnnotation
MetaAnnotation#value()            = Hello, World!

あなたが見ることができるように、注釈のクラスのインスタンスは、あなたがのために照会している注釈を持っていないプロキシクラスです。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=336344&siteId=1