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?

5
  • 3
    No, that's not possible in java. Reflection might get you the name of members, but not local variables. Commented Mar 15, 2017 at 10:49
  • I think you can achieve this by checking stackoverflow.com/questions/744226/… . Commented Mar 15, 2017 at 10:57
  • Possible duplicate of How do I print the variable name holding an object? Commented Mar 15, 2017 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 ? Commented Mar 24, 2017 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. Commented Mar 27, 2017 at 6:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.