Java – Way to print the variable name and variable value in java

java

String activityState = "resume";
DebugLog(activityState)

void DebugLog(String obj1) {}

How to make the DebugLog to print like this:

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:

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

Is there any way to do this?

Thanks in advance.

Best Solution

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