Matthias Ronge
Matthias Ronge

Reputation: 10102

Getting the name of a variable in Java

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?

Upvotes: 4

Views: 149

Answers (1)

Ad Infinitum
Ad Infinitum

Reputation: 3696

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.

Upvotes: 2

Related Questions