Close

Java - How to compile Java class to include method parameter names?

[Last Updated: May 20, 2018]

Java Tools & Commands Java 

We can obtain the names of the parameters of any method or constructor with the method java.lang.reflect.Executable.getParameters().
The classes Method and Constructor extend the class Executable and therefore inherit the method Executable.getParameters().
By default Java .class files do not store parameter names.
To store parameter names in a particular .class file, and thus enable the Reflection API to retrieve parameter names, we need to compile the source file with the -parameters option of the javac compiler.

Example

public class Task {

  public void execute(int num, String message) {
  }

  public static void main(String[] args) throws NoSuchMethodException {
      Method m = Task.class.getDeclaredMethod("execute", int.class, String.class);
      for (Parameter p : m.getParameters()) {
          System.out.printf("name: %s, type: %s%n", p.getName(), p.getType());
      }
  }
}

Compiling without -parameters option

D:\java-compile-parameter-names>javac Task.java
D:\java-compile-parameter-names>java Task
name: arg0, type: int
name: arg1, type: class java.lang.String

Compiling with -parameters option

D:\java-compile-parameter-names>javac -parameters Task.java
D:\java-compile-parameter-names>java Task
name: num, type: int
name: message, type: class java.lang.String

Specifying -parameters in pom.xml for maven build

  .............
    <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>10</source>
                    <target>10</target>
                    <encoding>UTF-8</encoding>
                    <compilerArgs>
                        <arg>-parameters</arg>
                    </compilerArgs>
                </configuration>
   </plugin>
 ..........

See Also