Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to print the variable name and variable value in java

Tags:

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.

like image 248
Navin GV Avatar asked Aug 01 '14 09:08

Navin GV


People also ask

How do you print variable names?

To print a variable's name: Use a formatted string literal to get the variable's name and value. Split the string on the equal sign and get the variable's name. Use the print() function to print the variable's name.

How do you print the value of the number variable?

As you might expect, printf can also print the values of variables. Here's an example: printf("The answer is %d\n", answer); The arguments to printf are a ``control'' string followed by the variables whose values you wish to print.

Can you print a string and a variable in Java?

It is also possible to use a mixture of strings and variables of other types as the argument of the print or println methods. In this case, Java will, again, automatically convert any non-string values to strings. Then the concatenation operator (+) can be used to produce one string for printing.


2 Answers

You can use java Reflection to get the variable name and the value. 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));
  }    

}
like image 173
Manorama Avatar answered Sep 28 '22 18:09

Manorama


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
like image 43
Mena Avatar answered Sep 28 '22 19:09

Mena