4

I'm currently writing a program in which I would like to access the variable names of local variables during execution of a program and pass them off externally. I'm aware that Java will dump local variable names during compilation unless compiled in debug mode.

After looking around some, it seems that JDI/JPDA is the way to go for this kind of work. Assuming ref refers to a ThreadReference, the following is what I have thus far:

ref.suspend();
StackFrame currentFrame = ref.frame(0);
List<LocalVariable> vars = currentFrame.visibleVariables();
ref.resume();

Two questions:

  1. Am I on the right track, or is there a better way to do this?
  2. How do I acquire the ThreadReference to set to ref? LocatableEvent seems to be what I need, but can anyone provide an example on how to use it?

Many thanks in advance!

cryptic_star
  • 1,863
  • 3
  • 26
  • 47
  • 4
    Why, oh Why? What possible reason is there to query the local variable *names* of a running method? – Joachim Sauer Jul 12 '10 at 13:06
  • Debugging tool - I'd like to pass the variables to a REPL of a Lisp for further evaluation/manipulation. It's just easier there, but if the user is passing in many variables, they would need to specify what the names of all of those vars are, or deal with having different variable names in the REPL. – cryptic_star Jul 12 '10 at 13:10
  • Possible duplicate of [build a simple debugger with jdi to set breakpoints and retrieve the value of a variable](https://stackoverflow.com/questions/47939691/build-a-simple-debugger-with-jdi-to-set-breakpoints-and-retrieve-the-value-of-a) – isnvi23h4 Dec 31 '17 at 15:18
  • @souparnomajumder Actually, I think that article is a duplicate of this one, since this one is much earlier. The answer should be posted here, and that one closed as a duplicate. – cryptic_star Jan 01 '18 at 16:15
  • @cryptic_star, yes the article was supposed to be duplicate, but the accepted answer has lost the link. hence the merge request – isnvi23h4 Jan 01 '18 at 16:39

2 Answers2

1

Not a lot of people have experience with this stuff.

Look elsewhere for an answer. I had links to code but they are no longer. Cannot delete this answer because it was accepted answer.

Romain Hippeau
  • 24,113
  • 5
  • 60
  • 79
0

Yes, you are on the right track!

For anyone who wants to try to get started with the JDI, the "Trace" example is invaluable:

http://www.docjar.com/docs/api/com/sun/tools/example/trace/package-index.html

It's a usable backbone. It shows you how to use events, which indeed will give you a ThreadReference. It also shows you how to start up the second JVM programmatically.

daveagp
  • 2,599
  • 2
  • 20
  • 19