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.
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.
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.
As a result of executing it again, I was able to get the argument name as expected as shown below.
x
y
Recommended Posts