Java8编译器的新特性-参数名字保留在字节码中

× 文章目录
  1. 1. Java编译器的新特性
    1. 1.1. 参数名字
  2. 2. Maven和Gradle使用方式
    1. 2.1. Maven使用介绍
    2. 2.2. Gradle使用介绍
  3. 3. 在IDE中的配置
    1. 3.1. Eclipse中的配置
    2. 3.2. 在IdeA中的配置

摘要:很长一段时间里,Java程序员一直在发明不同的方式使得方法参数的名字能保留在Java字节码中,并且能够在运行时获取它们(比如,Paranamer类库)。最终,在Java 8中把这个强烈要求的功能添加到语言层面(通过反射API与Parameter.getName()方法)与字节码文件(通过新版的javac的–parameters选项)中。由于中间件框架使用jdk8的新特性check参数顺序和签名,因此在使用RPC框架中,RPC服务端接口定义编译后的Class文件中加入了参数,但是在webApp中使用RPC Client在Eclipse等IDE中开发调试,由于生成class的时候Ide不会自动参数带进去。因此需要对IDE进行设置。

Java编译器的新特性

参数名字

很长一段时间里,Java程序员一直在发明不同的方式使得方法参数的名字能保留在Java字节码中,并且能够在运行时获取它们(比如,Paranamer类库)。最终,在Java 8中把这个强烈要求的功能添加到语言层面(通过反射API与Parameter.getName()方法)与字节码文件(通过新版的javac的–parameters选项)中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package org.xujin.jdk.parameter;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* @author xujin
*/
public class ParameterNames {
public static void main(String[] args) throws Exception {
Method method = ParameterNames.class.getMethod("main", String[].class);
for (final Parameter parameter : method.getParameters()) {
System.out.println("Parameter: " + parameter.getName());
}
}
}

如果不使用–parameters参数来编译这个类,然后运行这个类,会得到下面的输出:

1
Parameter: arg0

如果使用–parameters参数来编译这个类,程序的结构会有所不同(参数的真实名字将会显示出来):

1
Parameter: args

Maven和Gradle使用方式

Maven使用介绍

对于有经验的Maven用户,通过maven-compiler-plugin的配置可以将-parameters参数添加到编译器中去。

1
2
3
4
5
6
7
8
9
10
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<compilerArgument>-parameters</compilerArgument>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

针对Java 8最新发布的Eclipse Kepler SR2(请检查这里的下载说明)提供了非常实用的配置选项,可以通过下图的配置方式来控制编译器行为

Gradle使用介绍

在build.gradle中配置如下即可

1
2
3
4
5
6
7
compileJava {
sourceCompatibility = 1.8
targetCompatibility = 1.8
options.compilerArgs << '-parameters'
options.fork = true
options.forkOptions.executable = 'javac'
}

在IDE中的配置

有一种情况需要IDE编辑器在编译的时候,需要靠IDE自动的把参数等信息加到class文件中。

Eclipse中的配置

使用Eclipse进行本地调试时,需进行如下配置:
Preferences -> Java -> Compiler
JDK Compiliance -> “Compiler compliance level”设置为1.8
Classfile Generation -> “Store information about method parameters (usable via reflection)”设置为勾选
STS配置图

在IdeA中的配置

使用IDEA进行本地调试时,需进行如下配置:
Preferences -> “Build, Execution, Deployment” -> Compiler -> “Java Compiler”
“Project bytecode version”设置为1.8
“Additional command line parameters”添加”-parameters”

如果您觉得文章不错,可以打赏我喝一杯咖啡!