java java中打印变量名和变量值的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25077000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:17:43  来源:igfitidea点击:

Way to print the variable name and variable value in java

java

提问by Navin GV

String activityState = "resume";
DebugLog(activityState)

void DebugLog(String obj1) {}

How to make the DebugLogto print like this:

如何使DebugLog打印像这样:

activityState : resume

I used to write many print statement as logs at many places while debugging. I will write statements like

我曾经在调试时在很多地方写了很多打印语句作为日志。我会写这样的陈述

System.out.println("activityState : " + activityState);

I want a method to print the variable name and variable value. In C++, it can be done like the below:

我想要一种打印变量名称和变量值的方法。在 C++ 中,它可以像下面那样完成:

#define dbg(x) cout<< #x <<" --> " << x << endl ;

Is there any way to do this?

有没有办法做到这一点?

Thanks in advance.

提前致谢。

回答by Mena

There's no direct solution to get the variable name.

没有直接的解决方案来获取变量名。

However, in a context where you have many fields and don't want to manually print their state, you can use reflection.

但是,在您有许多字段并且不想手动打印其状态的上下文中,您可以使用反射。

Here's a quick example:

这是一个快速示例:

class MyPojo {
    public static void main(String[] args) {
        System.out.println(new MyPojo());
    }

    int i = 1;
    String s = "foo";

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (Field f: getClass().getDeclaredFields()) {
            try {
            result
            .append(f.getName())
            .append(" : ")
            .append(f.get(this))
            .append(System.getProperty("line.separator"));
            }
            catch (IllegalStateException ise) {
                result
                .append(f.getName())
                .append(" : ")
                .append("[cannot retrieve value]")
                .append(System.getProperty("line.separator"));
            }
            // nope
            catch (IllegalAccessException iae) {}
        }
        return result.toString();
    }
}

Output

输出

i : 1
s : foo

回答by Manorama

You can use java Reflection to get the variable name and the value. Here's an example code;

您可以使用 java Reflection 来获取变量名和值。这是一个示例代码;

public class Example{

  String activityState = "resume";

  public static void main(String[] args) {

       Example example = new Example();
       Class<?> c = example.getClass();
       Field field = c.getDeclaredField("activityState");
       System.out.println(field.getName());
       System.out.println(field.get(example));
  }    

}

回答by A4L

Since this is for debugging you could use instrumentation with aspectj, your code remains clean from the the debugging output statements and you can waeve the aspect as needed.

由于这是用于调试,您可以将检测与 aspectj 一起使用,您的代码从调试输出语句中保持干净,您可以根据需要改变方面。

Define a set(FieldPattern)point cut to catch all field assignements (join points)

定义set(FieldPattern)切入点以捕获所有字段分配(连接点)

public aspect TestAssignmentAspect {

    pointcut assigmentPointCut() : set(* *);

    after() : assigmentPointCut() {
        System.out.printf("%s = %s%n", thisJoinPoint.getSignature().getName(),
                String.valueOf(Arrays.toString(thisJoinPoint.getArgs())));
    }
}

Here is Test class

这是测试类

public class Test {

    public static String activityState = "stopped";

    public static void main(String[] args) {
        activityState = "start";

        doSomething();

        activityState = "pause";

        doSomeOtherthing();

        activityState = "resume";

        System.out.printf("the end!%n");
    }

    private static void doSomeOtherthing() {
        System.out.printf("doing some other thing...%n");
    }

    private static void doSomething() {
        System.out.printf("doing something...%n");
    }
}

If you run this example with the aspect weaved the output will be

如果您使用编织的方面运行此示例,则输出将是

activityState = [stopped]
activityState = [start]
doing something...
activityState = [pause]
doing some other thing...
activityState = [resume]
the end!

Explanation

解释

pointcut assigmentPointCut() : set(* *);

setpoint cut to catch assignments, the point joins, to any variable with any name, could also in the example be

set切点以捕获赋值,点连接到具有任何名称的任何变量,在示例中也可以是

pointcut assigmentPointCut() : set(String activityState);

The advice, the desired behavior when the given point cut matches

建议,在给定的切入点匹配所需的行为

after() : assigmentPointCut() { ... }

Informations about the point join can be accessed using the special reference thisJoinPoint.

可以使用特殊参考thisJoinPoint访问有关点连接的信息。