6

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

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

printing string value and its name .

0

4 Answers 4

4

You can print the variable name since Java 8 version: Java Reflection: How to get the name of a variable?

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, such as class name, package name, class attributes, etc...

Sign up to request clarification or add additional context in comments.

Comments

2

Java doesn't have a standard pre-processor to do this. Generally this is a good thing. In this case, you can use you own.

I suggest you use the debugger in your IDE for debugging your program, this avoids the need to write code to dump such debug statements to the console. Note: in Java there is little penalty for making your code always debuggable and most code ships with debug on.

If you breakpoint a line you can see all the values for local variable and what ever objects they point to. You can also go down the stack and see all the callers if you want.

Comments

2

In Java there's no preprocessor directives, so in this case there's no option, except for using IDE's shortcuts for this (usually, "soutv + tab", this works, for example, in InteliJ IDEA and Netbeans). So you'll get the output for default template:

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

Or you may implement the common method for doing this:

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

And run it in this way:

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

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

2 Comments

What's the poing for downvoting?
i do like your code , there is no issue , +1 enjoy :)
0

Usually you don't have preprocessing for Java. But a similar behaviour method would be:

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

1 Comment

You'll have to implement this kind of method for every variable, because usually, this output is needed for some several variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.