Getting the name of a method parameter

Viewed 34394

In Java 6, imagine I have the following method signature:

public void makeSandwich(Bread slice1, Bread slice2, List<Filling> fillings, boolean mustard)

I would like to know, at runtime, the value that was passed on to slice2 or any other parameter, the important bit here is that I want to get the value by parameter name.

I know how to get the list of parameter types with getParameterTypes or getGenericParameterTypes.

Ideally I would like to get a list of parameter names instead of types. Is there a way to do so?

8 Answers

Since Java 1.8, this can be done as long as the parameter names are in the class files. Using javac this is done passing the -parameters flag. From the javac help

-parameters    Generate metadata for reflection on method parameters

From IDEs you will need to look at the compiler settings.

If the parameter names are in the class files then here is an example of doing this

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class ParameterNamesExamples {

  public static void main(String[] args) throws Exception {
    Method theDoSomethingMethod = ExampleClass.class.getMethods()[0];
    // Now loop through the parameters printing the names
    for(Parameter parameter : theDoSomethingMethod.getParameters()) {
      System.out.println(parameter.getName());
    }
  }

  private class ExampleClass {
    public void doSomething(String myFirstParameter, String mySecondParameter) {
      // No-op
    }
  }
}

The output will depend on if the parameter names are in the class files. If they are the output is:

myFirstParameter
mySecondParameter

If not the output is:

arg0
arg1

More information on this from Oracle can be found at Obtaining Names of Method Parameters

Related