Add -parameters option to javac to get argument names by reflection

I wanted to get the argument name of the method using reflection in Java, but I'm a little stuck, so make a note.

In conclusion, at compile time, javac had to have the **-parameters option **. The procedure up to verification is as follows.

Problem: The argument name obtained by reflection becomes argN

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

public class GetArgsName {
	public static void main(String... args) throws NoSuchMethodException, SecurityException {

		Method m = Calc.class.getDeclaredMethod("add", int.class, int.class);
		Arrays.stream(m.getParameters())
			.map(Parameter::getName).forEach(System.out::println);
	}

	public static class Calc {
		public int add(int x, int y) {
			return x + y;
		}
	}
}

I thought that I could get the argument name with the above program, and when I executed it, the following result was obtained.

arg0
arg1

I wanted to get the argument names x and y, but for some reason I got them with argN.

Solution: Add -parameters option to javac

As a result of various investigations, Don Pisha's answer was written on the following site. Mr. Hishidama is always indebted to me. Lol

-Java Reflection Memo (Hishidama's Java Reflection Memo)

If you want to get the argument name by reflection, you need to add **-parameters option ** to javac. Also, when executing with Eclipse, it is OK if you check the following from Properties> Java Compiler of the project. Properties_for_amateras_allocate_claim_debt_fw.png

As a result of executing it again, I was able to get the argument name as expected as shown below.

x
y

Recommended Posts

Add -parameters option to javac to get argument names by reflection
[Kotlin] Get the argument name of the constructor by reflection
How to get parameters in Spark
[Rails] Add strong parameters to devise
Add arbitrary parameters to the URL output by <h: outputScript> <h: outputStylesheet> of JSF