简体   繁体   English

如何获取类的自定义注释列表?

[英]How to get list of custom annotations of a class?

My goal is to get list of custom annotations of a class.我的目标是获取类的自定义注释列表。

@RestController
public class HelloController {
  @Autowired
  private final IntegerService integerService;

  @Autowired
  private final BooleanService booleanService;

  public HelloController(IntegerService integerService, BooleanService booleanService) {
    this.integerService = integerService;
    this.booleanService = booleanService;
  }

  @GetMapping
  public String getHello() {
    return String.format("Hello %d %b", integerService.getRandomInt(), booleanService.getRandomBoolean());
  }
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RestController {
}

What I have done:我做了什么:

  1. do Class.forNameClass.forName
        Class<?> clazz = null;
        try {
          clazz = Class.forName("looslycoupled.controller.HelloController");
//          clazz = Class.forName(String.format("%s.%s", packageName, resource.substring(0, resource.lastIndexOf("."))));
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
        assert clazz != null;
        Annotation[] annotations = clazz.getDeclaredAnnotations();
        System.out.println(clazz.isAnnotationPresent(RestController.class));
        for (Annotation annotation : annotations) {
          System.out.println(annotation.getClass());
        }

My expected result: clazz.getDeclaredAnnotations() return [interface looslycoupled.framework.annotation.RestController]我的预期结果: clazz.getDeclaredAnnotations() return [interface looslycoupled.framework.annotation.RestController]

My actual result: it return [class com.sun.proxy.$Proxy1] .我的实际结果:它返回[class com.sun.proxy.$Proxy1]

  1. I tried to call clazz.isAnnotationPresent(RestController.class) .我试图调用clazz.isAnnotationPresent(RestController.class) It return true .它返回true So, I am not sure why clazz.getDeclaredAnnotations() return different result.所以,我不确定为什么clazz.getDeclaredAnnotations()返回不同的结果。

EDIT:编辑:

annotation.annotationType() does the job. annotation.annotationType()完成这项工作。

annotation.annotationType()完成这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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