Monday, December 23, 2013

Java 8 parameter name at runtime

Java 8 will be introducing an easier way to discover the parameter names of methods and constructors.

Prior to Java 8, the way to find the parameter names is by turning the debug symbols on at the compilation stage which adds meta information about the parameter names in the generated class files then to extract the information which is complicated and requires manipulating the byte code to get to the parameter names.

With Java 8, though the compilation step with debug symbols on is still required to get the parameter names into the class byte code, the extraction of this information is way simpler and is supported with Java reflection, for eg. Consider a simple class:

public class Bot {
    private final String name;
    private final String author;
    private final int rating;
    private final int score;

    public Bot(String name, String author, int rating, int score) {
        this.name = name;
        this.author = author;
        this.rating = rating;
        this.score = score;
    }
    
    ...
}    

theoretically, a code along these lines should get hold of the parameter names of the constructor above:

Class<Bot> clazz = Bot.class;
Constructor ctor = clazz.getConstructor(String.class, String.class, int.class, int.class);
Parameter[] ctorParameters =ctor.getParameters();

for (Parameter param: ctorParameters) {
    System.out.println(param.isNamePresent() + ":" + param.getName());
}

Parameter is a new reflection type which encapsulates this information. In my tests with Java Developer Preview (b120), I couldn't get this to work though!


Update: Based on a suggestion in the comments, the way to get the parameter name information into the class byte code is using a "-parameters" compiler argument, for eg this way through maven-compiler plugin:
<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-compiler-plugin</artifactId>
 <version>3.1</version>
 <configuration>
  <source>1.8</source>
  <target>1.8</target>
        <compilerArgument>-parameters</compilerArgument>
 </configuration>
</plugin>

References:

http://openjdk.java.net/jeps/118

2 comments:

  1. Compiler commandline argument '-parameters' will do the trick.
    Parameter names at runtime is an opt-in mechanism. Explained here http://parleys.com/play/524ededfe4b0f744c977b4b5 at 36:34

    ReplyDelete