Java注解与反射原理说明
作者:cakincqm 时间:2021-06-18 01:56:00
一 点睛
注解若想发挥更大作用,还需借助反射机制之力。通过反射,可以取得一个方法上声明的注解的全部内容。
一般有两种需求:
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));
}
...
}
来源:https://blog.csdn.net/chengqiuming/article/details/81604642
标签:java,反射,注解
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java金钱处理方法实例详解
2023-05-29 10:38:29
C#中异步和多线程的区别介绍
2021-08-23 07:06:49
C# 特殊的string类型详解
2022-02-10 14:11:59
关于Java中修饰符的总结(fina除外)
2023-11-22 23:15:57
Struts2 的国际化实现方式示例
2022-08-10 07:26:45
![](https://img.aspxhome.com/file/2023/3/70983_0s.jpg)
基于ElasticSearch Analyzer的使用规则详解
2023-09-28 14:41:04
![](https://img.aspxhome.com/file/2023/8/63698_0s.png)
SpringBoot实现PPT格式文件上传并在线预览功能
2023-07-22 14:44:56
![](https://img.aspxhome.com/file/2023/3/57403_0s.png)
解决try-catch捕获异常信息后Spring事务失效的问题
2022-11-15 03:17:33
Java中List转Map List实现的几种姿势
2022-10-23 19:19:57
Maven Plugin的@Mojo和@Execute的具体使用
2021-12-19 05:23:17
JAVA中使用FTPClient实现文件上传下载实例代码
2021-08-17 20:45:05
java+SpringBoot设计实现评教系统
2023-02-05 13:12:18
![](https://img.aspxhome.com/file/2023/6/69896_0s.jpg)
Java使用DualPivotQuicksort排序
2022-05-22 20:58:12
浅谈spring中scope作用域
2022-08-18 10:42:53
Flutter开发Widgets 之 PageView使用示例
2023-06-24 13:23:34
![](https://img.aspxhome.com/file/2023/1/120091_0s.jpg)
JDK1.8下载、安装和环境配置超详细教程(最新最完整)
2022-07-22 12:58:34
![](https://img.aspxhome.com/file/2023/5/62805_0s.jpg)
Java使用数组实现ArrayList的动态扩容的方法
2023-03-23 11:24:39
java json 省市级联实例代码
2021-11-13 18:50:35
jar包手动添加到本地maven仓库的步骤详解
2023-11-23 05:09:37
![](https://img.aspxhome.com/file/2023/5/59785_0s.png)
Java使用ExecutorService来停止线程服务
2023-01-25 12:10:56