查找某个类中是否有某个注解
来源:互联网 发布:韩端机器人编程软件 编辑:程序博客网 时间:2024/06/05 06:09
代码概述:
有三个类
1、MyAnnotation2--注释
2、UseMyAnnotation2--被测试的类
3、TestAnnotation2--进行测试的类
目的:
利用类反射技术
遍历出某个类中所有有@MyAnnotation注解的变量和方法(由下面注解类决定放的位置)
代码demo:
MyAnnotation2类:--注释类
package cn.hncu.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)//记录在.class文件中,并且在运行时保留"注释"@Target({ElementType.FIELD,ElementType.METHOD})//指定注解只能放在"变量"和"方法"上public @interface MyAnnotation2 {public String value() default "默认值...";}
UseMyAnnotation2类:--被测试的类:使用了@MyAnnotation注释
package cn.hncu.annotation;public class UseMyAnnotation2 {@SuppressWarnings("unused")@MyAnnotation2private int num = 10;@SuppressWarnings("unused")private String str = "hncu";@MyAnnotation2("aaa...")public void a(){}public void b(){}@MyAnnotation2("ccc...")public void c(){}}
TestAnnotation2:--测试类:查找UseMyAnnotation2类中有@MyAnnotation注解的变量和方法
package cn.hncu.annotation.test;import java.lang.reflect.Field;import java.lang.reflect.Method;import org.junit.Test;import cn.hncu.annotation.MyAnnotation2;/** * 思路: * 1、拿到Class对象 * 2、拿到所有的变量数组Field[] * 3、遍历Field[],如果变量上有@MyAnnotation2注释,输出-变量名 * 关键方法:★★f.isAnnotationPresent(MyAnnotation2.class) * * 4、同理:拿到并遍历所有方法,找到输出-方法名 */public class TestAnnotation2{private static final String CLASS_NAME = "cn.hncu.annotation.UseMyAnnotation2";@Testpublic void test1() throws Exception{Class<?> c = Class.forName(CLASS_NAME);//变量Field[] fs = c.getDeclaredFields();for(Field f:fs){if(f.isAnnotationPresent(MyAnnotation2.class)){System.out.println("有@MyAnnotation注释的变量:"+f.getName());}}//方法Method[] ms = c.getDeclaredMethods();for(Method m:ms){if(m.isAnnotationPresent(MyAnnotation2.class)){System.out.println("有@MyAnnotation注释的方法:"+m.getName());}}}}
运行结果:
0 0
- 查找某个类中是否有某个注解
- 查找某个数是否在矩阵中
- 判断数组中是否有某个元素
- C++代码片段01 - 字符串中查找是否有某个字符
- 判断一个表中是否存在某个字段 及 判断数据库中是否有某个
- php中查找数组中是否存在某个元素
- 系统盘是否有某个文件
- 判断是否有某个class
- Java中查找某个表是否在数据库已经存在
- 二维数组中查找某个数是否存在
- 查找二维排序数组中是否含有某个元素
- 循环递增数组中查找是否存在某个数
- 二维数组中查找是否存在某个值
- NSIS查找文本中是否包含某个字串
- Java 查找二维数组中是否含有某个数
- C#查找容器中是否包含某个状态
- 查找目录下所有文件中是否包含某个字符串
- php查找某个值是否存在于多维数组中
- (one day one problem)poj 2800 Joseph's Problem (数学)
- python递归,汉诺塔
- js性能优化
- 深度剖析空间配置器(三)内存处理函数
- 获取镜像
- 查找某个类中是否有某个注解
- postman的安装与使用(模拟Get和Post请求)
- 浏览器的操作
- JavaScript Date format(js日期格式化)
- 使用Jack编译
- 转载至http://cn.vuejs.org【vue.js对比其他框架】
- class no found :torg.springframework.web.context.ContextLoaderListener
- AndroidStudio文件夹结构视图讲解
- TensorFlow 最小二乘法拟合