是否可以从 Android/Java 或 iPhone/objective-C 的代码中获取变量名称以进行调试

use*_*184 2 java android objective-c

我经常使用如下定义的常量:

private static final int myConstant_x = 1;
private static final int myConstant_y = 2;

private int anyVariable;
anyVariable = myConstant_x
Run Code Online (Sandbox Code Playgroud)

在调试过程中,以某种方式访问​​日志输出的变量名称而不是值确实很有帮助。

Log.i (TAG,"this is debug output of anyVariable with constant name: " + ????);
Run Code Online (Sandbox Code Playgroud)

输出: “这是常量名称为 myConstant_x 的任何变量的调试输出”

代替

Log.i (TAG,"this is debug output of anyVariable with constant name: " + anyVariable);
Run Code Online (Sandbox Code Playgroud)

输出: “这是常量名称为 1 的任何变量的调试输出”

有什么办法吗?

我知道可以从代码中获取方法名称,但是有没有一种方法也可以以某种方式获取变量名称?

真的很有帮助

谢谢

编辑:更新/更正示例代码 - 对于第一个误导版本感到抱歉

Tho*_*mas 5

您可以使用反射获取类的字段并迭代它们。然后您就可以访问该名称和值。

像这样的东西:

public void logStaticFields( Class<?> clazz) throws IllegalAccessException {
  for( Field f : clazz.getDeclaredFields() ) {
    if( Modifier.isStatic( f.getModifiers() ) ) {
      boolean wasAccessible = f.isAccessible();
      f.setAccessible(true);
      Log.i (TAG, "this is debug output of static field " + f.getName() + ": " + f.get( null ) );
      f.setAccessible( wasAccessible );
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您只想记录常量(通常是静态最终的),您可以检查Modifier.isStatic( f.getModifiers() ) && Modifier.isFinal( f.getModifiers() ).

此方法还会暂时禁用访问检查,否则get()可能会抛出该错误IllegalAccessException。请注意,这可能仍然不起作用,具体取决于 JVM 的SecurityManager配置。

请注意,这仅适用于字段(类或实例变量)和方法参数,不适用于方法内的局部变量,因为这些变量没有反射信息。