How can I list all local variables in a Java method / function?

My main question: I know that you can generate class fields with reflection, even if you do not know the variable names, types, or even how many there are. However, is there a way to list all the variables in the current function or current scope, assuming I don't know what the variable names are?

In other words:

int x = 5; int y = 42; // some more code //Now I want to println x and y, but assuming I cannot use "x" or "y". 

I would also be pleased with the answer to this question: Say, I am allowed to store the names of all variables, does this help? eg:.

 Set<String> varNames = new HashSet<String>(); int x = 5; varNames.add("x"); int y = 42; varNames.add("y"); // some more code //Now with varNames, can I output x and y without using "x" or "y"? 

Why am I asking about this? I translated the XYZ language into java using ANTLR, and I would like to provide a simple method for displaying the entire state of a program at any given time.

The third possible solution that I would be happy with: if this is not possible in Java, is there any way to write bytecode for a function that visits the calling function and checks the stack? It would also solve the problem.

Which would be surprising if Java had the Python equivalent of eval() or php get_defined_vars() .

If that matters, I use Java 6, but everything that is needed for Java 5, 6, or 7 should be good.

Thanks!

+6
source share
2 answers

You cannot, as far as I know. At least not with normal Java code. If you can run the bytecode through some kind of post processor before you run it, and assuming that you are still building with debugging symbols turned on, then you can auto-generate the code to do this, but I don’t believe any way to access local variables in the current stack frame through reflection.

+4
source

If you do not want to use this as part of the normal way to run your program, but only for debugging, use the Java Platform Debugger Platform (JPDA) . Basically, you have to write your own debugger, set a breakpoint, and use the JDI API to query the state of the program. Local variables can be enumerated using StackFrame # visibleVariables () .

If the above is not an option, it will be very difficult. To get the variable names, you can parse the class file and read the table attribute of the local method variable. However, the only way to get the value of a local variable is through aload / iload / etc. bytecodes. They must be present in the method that you want to parse, so you cannot put this functionality in another helper method.

+1
source

Source: https://habr.com/ru/post/926603/


All Articles