簡體   English   中英

是否可以在運行時檢查 TYPE_USE 注釋是否存在於實現聲明中的接口上?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM