title: How do I list all local variables within a Java method / function?
body: <p>My main question: I know you can generically output 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 variables within the current function or current scope, assuming I do not know what the variable names are?</p>
  
  <p>In other words:</p>
  
  <pre><code>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".
  </code></pre>
  
  <p>I'd also be happy with an answer to this question:
  Let's say I'm allowed to store the names of all variables, does that help? e.g.:</p>
  
  <pre><code>Set&lt;String&gt; varNames = new HashSet&lt;String&gt;();
  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"?
  </code></pre>
  
  <p>Why am I asking this? I am translating XYZ language(s) to java using ANTLR, and I would like to provide a simple method to output the entire state of the program at any point in time. </p>
  
  <p>Third possible solution I'd be happy with: If this is not possible in Java, is there any way I can write byte-code for a function that visits the calling function and examines the stack? This would also solve the problem.</p>
  
  <p>What would be amazing is if Java had the equivalent of Python's <code>eval()</code> or php's <code>get_defined_vars()</code>. </p>
  
  <p>If it makes a difference, I'm using Java 6, but anything for Java 5, 6, or 7 should be good.</p>
  
  <p>Thanks!</p>