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.
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.
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.
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.
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));
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With