简体   繁体   中英

Is it possible to check at runtime whether or not a TYPE_USE annotation is present on an interface within a implements declaration?

Consider the following:

class A implements @X B, C, @X D {}

Is it possible to retrieve at runtime whether or not the implements declaration contains @X on each of the implementing interfaces?

So in the above example, for B the answer is yes, for C no and for D yes.

If it is, how would I achieve this?

Yes, this is possible with Class#getAnnotatedInterfaces() .

Returns an array of AnnotatedType objects that represent the use of types to specify superinterfaces of the entity represented by this Class object. (The use of type Foo to specify a superinterface in '... implements Foo' is distinct from the declaration of type Foo .)

[...]

For example:

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 {}
}

Output:

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!")

Other similar methods include:

Note that AnnotatedType has subtypes such as AnnotatedParameterizedType . That latter interface let's one get any annotations present on type arguments:

To know whether or not an AnnotatedType is an instance of a subtype requires an instanceof test (unless you already know for sure).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM