Getting local variables from a stack frame on the JVM
Asked Answered
P

2

12

Is there any way to get a map or other data structure of the local variables in the current scope in on the JVM without using a debugger? That is, to get the locals of the current stack frame?

I know that there are stacktrace objects, but StackTraceElement has no way to get access to any state. It just tells you what method was called where, but not what was in it.

Plutonium answered 31/8, 2009 at 19:35 Comment(0)
I
6

Variable names can be included in class files to aid debuggers, but javac doesn't do it by default. It requires the -g:vars option.

If it's present, a program could use a byte-code engineering library like ASM to access the local variable names and scope.

While this question is poorly phrased, I think it is a duplicate, and its answers may be relevant to your problem. I would add that if you don't care about the names, the local variable type and scope are always included in each method's attribute table.

Immaculate answered 31/8, 2009 at 19:42 Comment(0)
I
3

I don't think there is a way to do this. The compiler is always free to optimise away local variables, and providing such a method would prevent the compiler from taking advantage of this type of optimisation. When compiling a method, the compiler wouldn't be able to tell whether you called a hypothetical getLocalVariables() somewhere else in the program, so it would have to always put all declared local variables in such a map.

Idem answered 31/8, 2009 at 19:39 Comment(2)
The local variables are available in a map in the StackFrame. You can have a look here docs.oracle.com/javase/7/docs/jdk/api/jpda/jdi/com/sun/jdi/…Veliavelick
@VladManuelMureșan: that can throw AbsentInformationException which in fact it does for code compiled without -g. (Aside, even the getArgumentValues which only gets arguments, not all locals, is rather severely bugged, in practice.)Teniacide

© 2022 - 2024 — McMap. All rights reserved.