I'm currently trying to set some parameters from an external system. I have a request with named parameters, and in order to properly set the variables, I'm using annotated method arguments on my service calls. A simplified example might be
public Response loginAttempt(@MyParam("username") String username, @MyParam("password") String password) {
// login logic here
}
Clearly, annotating each argument name is annoying and duplicative (although, it does have the minor advantage of allowing me to change the name over different versions of the API, that's beside the point.)
It would be very, very handy if I was able to, in my reflective portion, to simply reference the name of the argument. Where now, I get the arguments and their annotations, note their order, make an array of that order, and run with it.
I know in previous version of Java this simply cannot be done. I also know Java is releasing versions faster than ever before, with newer and more modern features than ever before. Unfortunately, the signal to noise ratio with 15 year old information is too just not high enough to get a definitive answer. Is this something that can be done with modern Java?
Since Java 8 if you compile your code with javac -parameters
option and the method parameters will be retained, however there are drawbacks. The problem is primarily the class file size, take a look at Obtaining Names of Method Parameters docs.
You can use java.lang.reflect.Parameter.getName()
to get the method parameter name:
Method m = getClass().getMethods()[0];
System.out.println(m.getName()); // loginAttempt
Parameter[] parameters = m.getParameters();
for (Parameter parameter : parameters) {
System.out.print(parameter.getName() + " "); // username password
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With