首页 > 编程语言 >java 通过反射获取类上注解,方法上注解,注解里的值及方法参数

java 通过反射获取类上注解,方法上注解,注解里的值及方法参数

时间:2022-11-29 11:41:06浏览次数:58  
标签:java String value cl1 获取 类上 注解 method


****测试demo    git仓库地址: ​​https://github.com/alwaysInRoad/test-annotation-demo.git​

                   

项目为maven项目,导入时请注意!

说明:

      此类为本人开发的工具类,具体应用在什么地方呢。本人在实际项目中,权限管理这一块有所应用,应该是权限这一块有所需求而开发的。

应用场景说明:权限资源自动化生产时,用户点击界面的一键生成资源时,接口中就会遍历指定controller包下所有类,返回所有类名。再过反射获取类上注解,方法上注解及注解里的值。获取每一个url地址,与地址上的解释,生产一一对应的资源。

例如: 所用主要框架: spring boot、swagger2

 

1、反射获取类注解 @RequestMapping

//通过反射获取到类,填入类名
Class cl1 = Class.forName("");
//获取RequestMapping注解
RequestMapping anno = (RequestMapping) cl1.getAnnotation(RequestMapping.class);
//获取类注解的value值
String[] value = anno.value();
//将字符串数组转成字符串
StringBuilder sb = new StringBuilder();
for (String ele : value) {
sb.append(ele);
}
String classPath = sb.toString();

2、反射获取类注解 @GetMapping、@PutMapping、@PostMapping、@DeleteMapping

//获取类中所有的方法
Method[] methods = cl1.getDeclaredMethods();
for (Method method : methods) {
GetMapping getRequestMothed = (GetMapping) method.getAnnotation(GetMapping.class);
PutMapping putRequestMothed = (PutMapping) method.getAnnotation(PutMapping.class);
PostMapping postRequestMothed = (PostMapping) method.getAnnotation(PostMapping.class);
DeleteMapping deleteRequestMothed = (DeleteMapping)method.getAnnotation(DeleteMapping.class);
//获取类注解的value值
String[] value1 = getRequestMothed .value();
String[] value2 = putRequestMothed .value();
String[] value3 = postRequestMothed .value();
String[] value4 = deleteRequestMothed.value();
}

3、反射获取类注解 @ApiOperation

//获取类中所有的方法
Method[] methods = cl1.getDeclaredMethods();
for (Method method : methods) {
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
//获取方法上@ApiOperation注解的value值
apiOperationValue = apiOperation.value();
}

4、反射获取方法参数类表

//通过反射获取到类
String cl1 = Class.forName(string);
//获取类中所有的方法
Method[] methods = cl1.getDeclaredMethods();
for (Method method : methods) {
//获取方法参数注解
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
//获取注解名
String name = annotation.annotationType().getSimpleName();
}
}
}

结语:本人所有文章都立志写的简单易懂,戳中问题点。 当然了,简单的同时可能忽略了很多细节与详细,如有不足的地方,还请谅解并指出。 


标签:java,String,value,cl1,获取,类上,注解,method
From: https://blog.51cto.com/u_13002884/5894589

相关文章