反射机制获取@Target({ElementType.TYPE_USE})修饰的自定义注解

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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值