获取@Target({ElementType.TYPE_USE})修饰的自定义注解
ElementType.TYPE_USE是JDK8新推出的,可以在任意地方使用
- 使用场景:检测框架
public @NotNull("number") Integer number(@NotNull("不可为空") Integer num) {
return num;
}
OverStackFlow
由问题引出的解释:
https://stackoverflow.com/questions/37898797/elementtype-field-vs-elementtype-type-use
Oracle官方解释
:https://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html
In many cases, you do not have to write your own type checking modules. There are third parties who have done the work for you. For example, you might want to take advantage of the Checker Framework created by the University of Washington. This framework includes a NonNull module, as well as a regular expression module, and a mutex lock module. For more information, see the Checker Framework.
// 翻译:
在许多情况下,您不必编写自己的类型检查模块。有第三方已经替你完成了工作。例如,您可能希望利用华盛顿大学创建的Checker框架。这个框架包括一个NonNull模块、一个正则表达式模块和一个互斥锁模块。有关更多信息,请参见Checker框架。
使用
注意:其他ElementType
都可以通过@Retention(RetentionPolicy.RUNTIME)
可以在运行时通过反射机制获取到我们需要的注解
,但是ElementType.TYPE_USE
我是获取不到的,但是用其他API是可以或得到的。
下面开始获取使用TYPE_USE
修饰的注解
- 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE})
public @interface NotNull {
String value();
}
- Demo类
@NotNull("demo")
public class Demo {
@NotNull("age")
public Integer age = 21;
public @NotNull("number") Integer number(@NotNull("不可为空") Integer num) {
return num;
}
}
- 测试
Annotation[] annotations = Demo.class.getAnnotations();
System.out.println("类上的注解 = " + annotations[0]);
AnnotatedType[] numbers1 = Demo.class.getMethod("number", Integer.class).getAnnotatedParameterTypes();
Annotation[] annotations1 = numbers1[0].getAnnotations();
System.out.println("形参上的注解 = " + annotations1[0]);
AnnotatedType number = Demo.class.getMethod("number", Integer.class).getAnnotatedReturnType();
System.out.println("方法返回值的注解 = " + number.getAnnotation(NotNull.class));
NotNull notNull = Demo.class.getField("age").getAnnotatedType().getAnnotation(NotNull.class);
System.out.println("成员变量上的注解 = " + notNull);
// 常规方法获取不到, 但是我们用哪个ElementType.PARAMETER修饰时可以拿到的, 可以自行测试
Annotation[][] numbers2 = Demo.class.getMethod("number", Integer.class).getParameterAnnotations();
System.out.println("形参注解长度: " + numbers2[0].length);
总结:通过反射拿到
ElementType.TYPE_USE
修饰的注解可以用get…Type()方法获取