Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log in Java with variable name?

In a previous job, I was working in C++, and the company internal library had a logging macro where I could simply write LOG(somevariable), and it would output to standard out:

"variablename: variablevalue"

Does anyone know if there's a way to do this in Java?

I never thought to look at their code so I don't know how it was done. It was really useful though!

like image 491
RyanCheu Avatar asked Oct 06 '22 10:10

RyanCheu


1 Answers

If you use Eclipse you can use the "Watch Expression"-View to watch not only variables but also Method calls. See this.

If you just want to print a variable's value, you can use an Eclipse Template. Go to Windows->Preferences and look for the entry Java->Editor->Templates. Add a new template and call it for example "printvar". Add the following to the templates body:

System.out.println("${variable} = "+ ${variable});

Typing printvar during coding and then pressing CTRL+Space will generate the entered code using ${variable} as placeholder for the variable name. You will have to type the variable name only once, which saves time and typing.

BTW: The reason why you can create macros permitting syntactic sugar like LOG(variable_name) in C++, is beacuse C++ has a preprocessor: Java has none. There are implementations for Java preprocessors, but I think using one would be too much effort for such a simple problem like printing a variable's name followed by its value.

like image 73
Simon Avatar answered Oct 10 '22 01:10

Simon