Getting variable name in Java

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

Possible use case: in statements. Given a type statement

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

Depending on your IDE, if you reorganize the code, rename the variable, it cannot automatically change the entries in the lines. Possible result:

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

It would be nice if something like this:

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

Possible?

+4
source share
1 answer

I'm not sure if this is possible before java 8, but with java 8, you can follow the following link and achieve what you want to do.

A summary of this is given as follows:

.

+2

Source: https://habr.com/ru/post/1672343/


All Articles