JDK8保留参数原本名称

作者:じ☆ve宝贝

发布时间:2018-12-06T17:44:09

在JDK8之前,java编译器会忽略我们编写代码时候设定的参数名,比如在mybatis框架中,我们可以使用@Param注解来让mybatis知道参数名。

public interface DemoMapper {
 
    List<Card> getCardList(@Param("cardIds") List<Integer> cardIds);
 
    Card getCard(@Param("cardId")int cardId);
}

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

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("isNamePresent: " + parameter.isNamePresent());
			System.out.println( "Parameter: " + parameter.getName() );
		}
	}
}

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

isNamePresent: false
Parameter: arg0

如果使用–parameters参数来编译这个类,参数的真实名字将会显示出来:

isNamePresent: true
Parameter: args

如果是maven项目,可以配置maven编译插件:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-compiler-plugin</artifactId>
	<version>3.1</version>
	<configuration>
		<compilerArgument>-parameters</compilerArgument>
		<encoding>UTF-8</encoding>
		<source>1.8</source>
		<target>1.8</target>
	</configuration>
</plugin>

java编译

javac -parameters ***.java,

eclipse配置

idea配置 Build,Execution,Deployment->Java Compiler 在框内填写-parameters参数