[英]How 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 {
}
我做了什么:
Class.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());
}
我的预期结果: clazz.getDeclaredAnnotations()
return [interface looslycoupled.framework.annotation.RestController]
我的实际结果:它返回[class com.sun.proxy.$Proxy1]
。
clazz.isAnnotationPresent(RestController.class)
。 它返回true
。 所以,我不确定为什么clazz.getDeclaredAnnotations()
返回不同的结果。编辑:
annotation.annotationType()
完成这项工作。
annotation.annotationType()
完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.