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).
- package com.javacodegeeks.java8.parameter.names;
- import java.lang.reflect.Method;
- import java.lang.reflect.Parameter;
- 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() );
- }
- }
- }
If you compile this class without using –parameters argument and then run this program, you will see something like that:
- Parameter: arg0
With –parameters argument passed to the compiler the program output will be different (the actual name of the parameter will be shown):
- Parameter: args
For experienced Maven users the –parameters argument could be added to the compiler using configuration section of the maven-compiler-plugin:
- <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>
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
Additionally, to verify the availability of parameter names, there is a handy method isNamePresent() provided by Parameter class.