There is some βspecial caseβ that may have a workaround for this (which is said by others), but the most important question is: why would you do this (by printing out the variable name)?
In my experience, 99.9% of such questions (how to print the variable name? How to get the variable depends on the user entering the variable name, etc.) are actually raised by the programming novice, and they just made the wrong assumptions and projects. The goal they are trying to achieve can be accomplished with a more suitable design.
Edit
Honestly, I still don't think you are trying to do this, but at least I think the following working answer:
This is more or less a combination of the previous answer:
(Don't try to compile, but at least this gives you an idea)
class Constants { public static final int FOO = 123; public static final int BAR = 456; private static Map<Integer, String> constantNames = null; public static String getConstantName(int constVal) { if (constantNames == null) { Map<Integer, String> cNames = new HashMap<Integer, String>() for (Field field : MyClass.class.getDeclaredFields()){ if ((field.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) != 0) { && int.class == field.getType()){
Assuming you want a constant name, just do:
Constants.getConstantName(123); // return "FOO"
source share