本文共 1369 字,大约阅读时间需要 4 分钟。
在mybatis的源码学习中,知道了mybatis可以开始在Java8将参数名称作为映射名称,Java8一项新的特性——在class文件中保留参数名。
Java8中反射包出现了新的方法,Method.getParameters(),可以获取Parameter数组。而以前只能使用Method.getParameterTypes()获取Class数组。
import java.lang.reflect.Method;import java.lang.reflect.Parameter;public class TestMethodParams { public String test(String name, int age) { return name; } public static void main(String[] args) throws NoSuchMethodException, SecurityException { Method method = TestMethodParams.class.getMethod("test",String.class,int.class); for (Parameter p : method.getParameters()) { System.out.println("parameter: " + p.getType().getName() + ", " + p.getName()); } }}
如果我们不做其他设置,我们可以得到以下结果
parameter: java.lang.String, arg0
parameter: int, arg1 1 2 这是因为Java8必须得打开编译开关才能使用,打开之后结果如下:使用原生编译器javac,直接使用javac -parameters
***.java,得到的class文件将保留参数名称。
Window->Preferencces->Java->Compiler 然后勾选红框选中值
File->Setting
Build,Execution,Deployment->Java Compiler 在框内填写-parameters参数
<plugin>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin>