【Demo 地址】
https://github.com/alwaysInRoad/test-annotation-demo.git
說明:
此類爲本人開發的工具類,具體應用在什麼地方呢。本人在實際項目中,權限管理這一塊有所應用,應該是權限這一塊有所需求而開發的。
應用場景說明:權限資源自動化生產時,用戶點擊界面的一鍵生成資源時,接口中就會遍歷指定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();
}
}
}