Java print string C ++ equivalent

What would be the equivalent in Java of C ++ code:

#define printVar(var) cout<<#var<<"="<<var; 

print line value and its name.

+6
source share
4 answers

You can print a variable name from Java 8: Java Reflection: how to get the variable name?

You can print the value using something like: System.out.println(String.valueOf(var));

Through Java reflection, you can get more information from a variable, for example, class name, package name, class attributes, etc ...

+4
source

There are no preprocessor directives in Java, so in this case there is no option other than using IDE shortcuts for this (usually "soutv + tab", this works, for example, in InteliJ IDEA and Netbeans). Thus, you will get the result for the default template:

 System.out.println("var = " + var); 

Or you can implement a general method for this:

 void printVariable (Object variable, String name) { System.out.println (name + " = " + variable); } 

And run it like this:

 printVariable (var, "var"); printVariable (anotherVar, "anotherVar"); 

UPDATE: according to this answer in Java 8 there might be a way to do this through reflection (in some cases)

+2
source

Java does not have a standard preprocessor for this. This is generally good. In this case, you can use your own.

I suggest you use a debugger in your IDE to debug your program, this avoids the need to write code to output such debugging commands to the console. Note: in Java, there is no penalty that your code is always debugged, and most code is sent with debugging.

If you stop the line, you will see all the values ​​for the local variable and what they are pointed to by the objects. You can also go down the stack and see all the callers if you want.

+2
source

Usually you do not have preprocessing for Java. But a similar method of behavior would be as follows:

 public static void printVar(String var) { System.out.print("var=", var); } 
0
source

Source: https://habr.com/ru/post/969525/


All Articles