简体   繁体   English

在Java中打印变量名称和变量值的方法

[英]Way to print the variable name and variable value in java

String activityState = "resume";
DebugLog(activityState)

void DebugLog(String obj1) {}

How to make the DebugLog to 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. 提前致谢。

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

You can use java Reflection to get the variable name and the value. 您可以使用java Reflection获得变量名称和值。 Here's an example code; 这是一个示例代码;

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));
  }    

}

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(* *);

set point 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访问有关点连接的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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