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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值