Java how to print all local variables?

后端 未结 6 1993
长情又很酷
长情又很酷 2021-01-12 04:25

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:

Syste         


        
相关标签:
6条回答
  • 2021-01-12 04:33

    It's not simple to read the values of local variables at runtime, even if you're a debugger. If there are no debug symbols in your class, there is no way at all to see local variables, even if you use a debugger.

    The most simple solution to see the values is printing them with System.out.println() or to use logging (slf4j).

    If you want to example local variables at runtime without changing the code, you can try AOP (Aspect-oriented programming). Or you can use the same API that a debugger uses to examine the running VM.

    0 讨论(0)
  • 2021-01-12 04:35

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

    int i = 42;
    System.out.println("i:" + i);
    
    0 讨论(0)
  • 2021-01-12 04:38
    • Just print them out to the debugger. (Debugging with Eclipse)

    OR

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

    OR

    • User Log4J : http://en.wikipedia.org/wiki/Log4j
    0 讨论(0)
  • 2021-01-12 04:39

    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.

    0 讨论(0)
  • 2021-01-12 04:43

    What do you mean by "examining" ? Try a System.out.println(yourvariable), or (yourvariable.toString()) if it's an object. It'll display it in the console.

    0 讨论(0)
  • 2021-01-12 04:49

    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.

    0 讨论(0)
提交回复
热议问题