简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM