Java通過反射獲取Controller類、方法上注解和注解里的值


背景

在進行權限管理方面的開發過程中,嘗試通過反射獲取匹配的方法的注解,然后得到匹配路徑進行鑒權。

反射獲取類的注解@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();

反射獲取類注解 @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();
} 

反射獲取類注解 @ApiOperation

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

反射獲取方法參數類表

//通過反射獲取到類
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();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM