【转载】JDK8新特性:将参数名带到字节码文件

Published on 2022-01-05 18:26 in 分类: 随笔 with 狂盗一枝梅
分类: 随笔

转载自文章:https://blog.csdn.net/qq_22017543/article/details/98103704

在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() );
         }
     }
 }

parameter.isNamePresent() 查看是否开启参数。

如果是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>

在eclipse中可以在 Preferences -- compiler -- store information about method

parameters(usable via reflection) 打开。


#java #maven
目录