Java how to print all local variables?

90,823

Solution 1

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.

Solution 2

I want to have something like: System.out.printLocals();

Also it should be great to have something like: System.out.printMembersOf(someObjectInstance);

Just about every Java class has a toString method. You override that method, and you can get a string that represents what you're asking for.

Eclipse Helios, among other IDEs, will generate a basic toString method for you.

Solution 3

OR

  • Print out to the console: (System.out.println("var"))

OR

Solution 4

You can use System.out.println to print out variables. Example:

int i = 42;
System.out.println("i:" + i);
Share:
90,823
denys
Author by

denys

Updated on March 15, 2020

Comments

  • denys
    denys over 4 years

    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);
    
  • denys
    denys over 13 years
    this will not work for case: public void foo(int k, String s) { System.out.printLocals(); } // expected output is the same as for System.out.ptintln("k: " + Integer.toString(k)); System.out.ptintln("s: " + s);
  • Gilbert Le Blanc
    Gilbert Le Blanc over 13 years
    @denys: You're correct. However, there's no reason you couldn't code a toLocalString method for each of the methods you wanted local variables.
  • Ciro Santilli OurBigBook.com
    Ciro Santilli OurBigBook.com over 9 years
    On jdb there is locals.
  • Anurag Awasthi
    Anurag Awasthi almost 7 years
    BCEL hmm, ugly eh? I'd rather use dump(ar1, ar2m,..)