3. New Features in Java compiler

3.1. Parameter names

Literally for ages Java developers are inventing different ways to preserve method parameter names in Java byte-code and make them available at runtime (for example, Paranamer library). And finally, Java 8 bakes this demanding feature into the language (using Reflection API and Parameter.getName() method) and the byte-code (using new javac compiler argument –parameters).

  1. package com.javacodegeeks.java8.parameter.names;
  2.  
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Parameter;
  5.  
  6. public class ParameterNames {
  7. public static void main(String[] args) throws Exception {
  8. Method method = ParameterNames.class.getMethod( "main", String[].class );
  9. for( final Parameter parameter: method.getParameters() ) {
  10. System.out.println( "Parameter: " + parameter.getName() );
  11. }
  12. }
  13. }

If you compile this class without using –parameters argument and then run this program, you will see something like that:

  1. Parameter: arg0

With –parameters argument passed to the compiler the program output will be different (the actual name of the parameter will be shown):

  1. Parameter: args

For experienced Maven users the –parameters argument could be added to the compiler using configuration section of the maven-compiler-plugin:

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

Latest Eclipse Kepler SR2 release with Java 8 (please check out this download instructions) support provides useful configuration option to control this compiler setting as the picture below shows.

Picture 1. Configuring Eclipse projects to support new Java 8 compiler –parameters argument.
Picture 1. Configuring Eclipse projects to support new Java 8 compiler –parameters argument

Additionally, to verify the availability of parameter names, there is a handy method isNamePresent() provided by Parameter class.