好程序员Java培训分享注解与反射原理说明

本文介绍了Java中注解的应用及反射机制的使用方法。主要讲述了如何通过反射获取方法上的所有注解,以及如何判断特定注解的存在。通过源码解析了getAnnotations()和getAnnotation()方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好程序员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 getAnnotation(Class annotationClass) {
return super.getAnnotation(annotationClass);
}

}
public abstract class Executable extends AccessibleObject
implements Member, GenericDeclaration {

public T getAnnotation(Class annotationClass) {
Objects.requireNonNull(annotationClass);
//获得指定注解类的信息
return annotationClass.cast(declaredAnnotations().get(annotationClass));
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值