栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

反射机制获取@Target({ElementType.TYPE

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

反射机制获取@Target({ElementType.TYPE

获取@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()方法获取

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/396965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号