I frequently use constants defined like:
private static final int myConstant_x = 1;
private static final int myConstant_y = 2;
private int anyVariable;
anyVariable = myConstant_x
during debugging it would be really helpful to somehow access the name of the variable for log output instead of the value.
Log.i (TAG,"this is debug output of anyVariable with constant name: " + ????);
with output:
“this is debug output of anyVariable with constant name: myConstant_x”
instead of
Log.i (TAG,"this is debug output of anyVariable with constant name: " + anyVariable);
with output:
“this is debug output of anyVariable with constant name: 1”
Is there any way?
I know one can get the method name from within code but is there a way to get the variable name too somehow?
Would be really helpful
Thanks
EDIT: updates/corrected the example code – sorry for the first misleading version
You could get the fields of a class using reflection and iterate over them. You’d then have access to the name and the value.
Something like this:
If you want to only log constants (which normally are static final) you could check for
Modifier.isStatic( f.getModifiers() ) && Modifier.isFinal( f.getModifiers() ).This method also temporarily disables access checks, otherwise
get()might throw thatIllegalAccessException. Note that this might still not work, depending on your JVM’sSecurityManagerconfiguration.Note that this only works for fields (class or instance variables) and method parameters, not for local variables within a method since theres no reflection information for those.