adam bien's blog

Getting Method Parameter Names via Reflection and Apache Maven 📎

If you try to get the method parameter names from e.g.:

public void methodWithParameters(String first, int second) {
}

...via reflection:


@Test
public void accessParameterNames() throws Exception {
    var method = this.getClass()
    .getMethod("methodWithParameters",String.class,int.class);
    var parameters = method.getParameters();
    for (var parameter : parameters) {
        var name = parameter.getName();
        System.out.println(name);
    }
}

...you will get the following output:


arg0
arg1    

To get the actual parameter names, you will have to compile the code with the javac -parameters (Generate metadata for reflection on method parameters) switch.

In a maven project, you will have to use newer version of compiler plugin first (the default is ~3.1):


<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
</plugin>   

...then activate compiler parameters with


<properties>
    <maven.compiler.parameters>true</maven.compiler.parameters>
</properties>    

...now mvn test yields:


first
second