Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to print all local variables?

I have a method and want to examine variables inside it without debugging - is it possible in Java?

I do not want to write tons of code like:

System.out.println("a: " + a);

I want to something like:

System.out.printLocals();

Also it should be great to have something like:

System.out.printMembersOf(someObjectInstance);
like image 749
denys Avatar asked Mar 18 '11 16:03

denys


People also ask

How do you call a local variable in Java?

Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference. VariableName.

How do you declare all variables in Java?

To declare a variable in Java, all that is needed is the data type followed by the variable name: int numberOfDays; In the above example, a variable called "numberOfDays" has been declared with a data type of int. Notice how the line ends with a semi-colon.

How do you make a local variable global in Java?

Initialize the variable outside a block, and set it inside the block. You will have access to it outside. Save this answer.


1 Answers

Well, you can write a method with a varargs parameter and just write:

dump(variable1, variable2, variable3, variable4, ...);

It's not ideal, but it will be enough in some circumstances. There's no way to automatically grab all the local variables from a method and dump them though.

You might consider some sort of bytecode manipulation (e.g. with BCEL) which could do it... but it would be pretty ugly.

like image 134
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet