Java how to print all local variables?

denys picture denys · Mar 18, 2011 · Viewed 90.4k times · Source

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);

Answer

Jon Skeet picture Jon Skeet · Mar 18, 2011

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.