4

Is it possible to get the name of a variable in Java at runtime?

Possible use case: in assertions. Given an assertion like

assert percval >= 0 && percval <= 100 : "percval out of range: " + percval;

Depending on your IDE, if you refactor the code, rename the variable, it may not automatically change occurrences in strings. Possible result:

assert percentage >= 0 && percentage <= 100 : "percval out of range: " + percentage;

Would be nice if there was something like this:

assert percval >= 0 && percval <= 100 : nameOf(percval) + " out of range: " + percval;

Possible?

Matthias Ronge
  • 9,403
  • 7
  • 47
  • 63
  • 3
    No, that's not possible in java. Reflection might get you the name of members, but not local variables. – f1sh Mar 15 '17 at 10:49
  • I think you can achieve this by checking https://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable . – screab Mar 15 '17 at 10:57
  • Possible duplicate of [How do I print the variable name holding an object?](http://stackoverflow.com/questions/3959206/how-do-i-print-the-variable-name-holding-an-object) – alain.janinm Mar 15 '17 at 14:01
  • Did my answer solve your problem? I am curious because I did not use it self and wonder if it is possible with I have given link to ? – Ad Infinitum Mar 24 '17 at 10:40
  • I didn’t try it either since the project still develops on Java 7 only. If it works, it would be what I was looking for. I will come to it later when switching to Java 8. I do not know when this will happen. – Matthias Ronge Mar 27 '17 at 06:50

1 Answers1

2

I am not sure if it was possible before java 8 but with java 8, you can follow the following link and achieve what you want to do.

The summary of this is given as follows;

Provide a mechanism to easily and reliably retrieve the parameter names of methods and constructors at runtime via core reflection.

Ad Infinitum
  • 3,560
  • 27
  • 33