• 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();
            }
        }
    }
    
  • 相关阅读:
    Linux常用命令及示例(全)
    linux下安装配置svn服务器
    Kafka、Redis和其它消息组件比较
    ORACLE定时备份方案
    mysql库表优化实例
    携程apollp快速部署DVE集群
    windows 安装Zookeeper 配置集群
    Ubuntu 18.04 LTS 修改Host,使用Host访问
    PowerShell因为在此系统中禁止执行脚本......
    常用第三方工具的Docker命令
  • 原文地址:https://www.cnblogs.com/hnxbp/p/14975288.html
Copyright © 2020-2023  润新知