Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable name semantically in Java

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?

like image 321
corsiKa Avatar asked Mar 19 '19 15:03

corsiKa


Video Answer


1 Answers

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
}
like image 87
Karol Dowbecki Avatar answered Oct 21 '22 17:10

Karol Dowbecki