Java注解与反射原理说明

一 点睛

注解若想发挥更大作用,还需借助反射机制之力。通过反射,可以取得一个方法上声明的注解的全部内容。
一般有两种需求:

1 取得方法中全部的注解,通过调用getAnnotations来实现。
2 判断操作是否是指定注解,通过调用getAnnotation来实现。

下面从源码角度来说明怎样获取这些注解信息。

二 源码导读——取得方法中全部的注解
public class AccessibleObject implements AnnotatedElement {
  ...
  //取得全部Annotation
  public Annotation[] getAnnotations() {
    return getDeclaredAnnotations();
  }  
  ...
}
public final class Method extends Executable {
  ...
  public Annotation[] getDeclaredAnnotations() {
    //针对Method类,需要调用父类的getDeclaredAnnotations方法
    return super.getDeclaredAnnotations();
  }  
  ...
}
//Method的父类Executable的getDeclaredAnnotations实现全部注解信息的获取
public abstract class Executable extends AccessibleObject
  implements Member, GenericDeclaration {
  ...
  public Annotation[] getDeclaredAnnotations() {
    return AnnotationParser.toArray(declaredAnnotations());
  }  
  ...
}
三 源码导读——判断操作是否是指定注解
public final class Method extends Executable {
  ...
  取得指定Annotation
  public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
    return super.getAnnotation(annotationClass);
  }
  ...
}
public abstract class Executable extends AccessibleObject
  implements Member, GenericDeclaration {
  ...
  public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
    Objects.requireNonNull(annotationClass);
    //获得指定注解类的信息
    return annotationClass.cast(declaredAnnotations().get(annotationClass));
  }  
  ...
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值
为了学习工作与休闲娱乐互不冲突,现新建圈【码农茶水铺】用于程序员生活,爱好,交友,求职招聘,吐槽等话题交流,希望各位大神工作之余到茶水铺来喝茶聊天。群号:603619042
还有大量的面试题,视频资源共享,
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值