zoukankan      html  css  js  c++  java
  • 通过反射获取函数参数名称

    通过javassit获取

    参见 http://blog.csdn.net/viviju1989/article/details/8529453 这篇文章的方法一,实现比较麻烦,就不说了。

    通过spring的LocalVariableTableParameterNameDiscoverer

    public static List<String> getParamterName(Class clazz, String methodName){
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                if (methodName.equals(method.getName())) {
                    String[] params = u.getParameterNames(method);
                    return Arrays.asList(params);
                }
            }
    
            return null;
        }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    如果不用Class,而是通过spring注入的实例,然后instance.getClass.getDeclaredMethods()则无法得到参数名,调试时看到方法名称是通过jdk代理过的,拿不到参数名。

    通过Java8的Parameter类

    在Java 8之前的版本,代码编译为class文件后,方法参数的类型是固定的,但参数名称却丢失了,这和动态语言严重依赖参数名称形成了鲜明对比。现在,Java 8开始在class文件中保留参数名,给反射带来了极大的便利。jdk8增加了类Parameter

    public static List<String> getParameterNameJava8(Class clazz, String methodName){
            List<String> paramterList = new ArrayList<>();
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                if (methodName.equals(method.getName())) {
                    Parameter[] params = method.getParameters();
                    for(Parameter parameter : params){
                        paramterList.add(parameter.getName());
                    }
    
                }
            }
    
            return paramterList;
        }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    如果编译级别低于1.8,得到的参数名称是无意义的arg0、arg1…… 
    遗憾的是,保留参数名这一选项由编译开关javac -parameters打开,默认是关闭的。 
    注意此功能必须把代码编译成1.8版本的class才行。 
    idea设置保留参数名:

    在 preferences-》Java Compiler->设置模块字节码版本1.8,Javac Options中的 Additional command line parameters: -parameters

    参考资料

    在Java 8中获取参数名称

  • 相关阅读:
    《JAVA多线程编程核心技术》 笔记:第四章、Lock的使用
    服务器负载粗略估算
    spring事务传播性理解
    BlockingQueue 阻塞队列2
    六大原则
    mycat之schema.xml理解
    mycat分库读写分离原理
    sqlservere连接问题
    java代码添加mysql存储过程,触发器
    Amoeba+Mysql实现读写分离+java连接amoeba
  • 原文地址:https://www.cnblogs.com/exmyth/p/8672786.html
Copyright © 2011-2022 走看看