Java 8——保存参数名称

一.详述

在很多情况下,程序需要保存方法参数名称,如Mybatis中的mapper和xml中sql的参数绑定。但是在java 8之前的编译器是不支持保存方法参数名至class文件中的。

所以很多框架都采用注解的形式,如Mybatis中采用@Param注解来保存参数名称,用于和xml中sql的参数占位匹配绑定。

但是经过强烈的愿望要求,java 8终于将这一特性引入进来。默认情况下,javac编译器编译时不会保存方法参数名称。在javac编译时增加"-parameters"参数即可:

-parameters
Stores formal parameter names of constructors and methods in the generated class file so that the method java.lang.reflect.Executable.getParameters from the Reflection API can retrieve them.

可以参考文档javac中的描述:

-parameters是存储构造方法和普通方法的形参名称到编译生成的class文件中,在运行时可以通过反射API获取参数名称。

java.lang.reflect.Executable  
   |_java.lang.reflect.Constructor
   |_java.lang.reflect.Method

如果是maven工程:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <!-- 增加编译参数-parameters -->
                <compilerArgument>-parameters</compilerArgument>
            </configuration>
        </plugin>
    </plugins>
</build>

二.示例

public  class MethotdParamsParser {
    public void query(String id) {

    }

    static void parseMethodParams() throws NoSuchMethodException {
        Method m = MethotdParamsParser.class.getMethod("query", String.class);
        Parameter[] ps = m.getParameters();
        for (Parameter p : ps) {
            System.out.println(p.getName());
            System.out.println(p.getModifiers());
            System.out.println(p.getParameterizedType().getTypeName());
        }
    }

    public static void main(String[] args) throws NoSuchMethodException {
        parseMethodParams();
    }
}

以上执行结果:

id
0
java.lang.String
参考

Constructor/Method Parameters Metadata Available Via Reflection in JDK 8

原文地址:https://www.cnblogs.com/lxyit/p/9442782.html