0

Is it possible to refer to a variable name in a Java method?

E.g. imagine a method stateTheObvious(String personOrThing) that returns the sentence:

"[personOrThing - the value of the variable] is the [name of the variable as it was the parameter calling the method]."

Examples:

String queen = "Elizabeth II";
stateTheObvious(queen);
-> "Elizabeth II is the queen."

String end = "This";
stateTheObvious(end);
-> "This is the end."

Possible? If yes, how?

EDIT: My main motivation is a generic method to create URL parameters: String lastname = "Smith";
buildUrlParameter(lastname);

KnightMove
  • 23
  • 1
  • 7
  • 3
    Does this answer your question? [Java Reflection: How to get the name of a variable?](https://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable) – byxor Nov 14 '19 at 13:39
  • As a side not - you do NOT want to use that. Don't use reflection unless you're very experienced Java dev and know what you're doing. – Amongalen Nov 14 '19 at 13:40
  • Be aware that if you were somehow able to get the name of the parameter, you'd probably only be able to see the parameter name, and not the name of the variable that was passed in. You'd need to pass an extra String parameter into your function. – byxor Nov 14 '19 at 13:42
  • Instead of asking if it's possible, explain why you want to do this and perhaps another alternative can be suggested. – WJS Nov 14 '19 at 13:49
  • @WJS My main motivation is a generic way to build URL parameters in frontend automated testcases - e.g. lastName=Smith. (Of course this requires to always choose the right parameter name.) – KnightMove Nov 14 '19 at 13:57

2 Answers2

0

There is a technique, that I think was down to Cameron Purdy from way back when blogs were a thing.

First you need to find the file name and line number. You can find the file number by creating an exception and examining the stack trace. You also need to the file. This can be derived from the class name, possibly. Alternatively java.lang.StackWalker.getCallerClass (since Java SE 13) and get hold of the CodeSource.

Once you have the file name and number, you can go find the source line and roughly parse it to find the expression text passed to your function.

Obviously, this is really only suitable for debugging, but that seems to be the task anyway.

Alternatively, you could preprocess your source files. For instance, the C preprocessor should work fine.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
0

Perhaps you could use a HashMap.

You can do

  1. Map<String, String> to map one string to another.

  2. Map<String,List<String>> to map a string to a list of strings.

  3. Map<String,Map<String,String>> to map a string to another map.

The Types of the maps and lists can vary to your specific needs.

WJS
  • 36,363
  • 4
  • 24
  • 39