简体   繁体   English

Java访问本地变量名称

[英]Java Access to Local Variable Names

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. 我知道Java会在编译期间转储本地变量名,除非在调试模式下编译。

After looking around some, it seems that JDI/JPDA is the way to go for this kind of work. 看了一下之后,似乎JDI / JPDA就是这种工作的方式。 Assuming ref refers to a ThreadReference , the following is what I have thus far: 假设ref引用了ThreadReference ,以下是我到目前为止的内容:

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 ? 如何获取ThreadReference以设置为ref LocatableEvent seems to be what I need, but can anyone provide an example on how to use it? LocatableEvent似乎是我需要的,但任何人都可以提供一个如何使用它的例子吗?

Many thanks in advance! 提前谢谢了!

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. 无法删除此答案,因为它已被接受答案。

Yes, you are on the right track! 是的,你走在正确的轨道上!

For anyone who wants to try to get started with the JDI, the "Trace" example is invaluable: 对于任何想要尝试开始使用JDI的人来说,“跟踪”示例非常宝贵:

http://www.docjar.com/docs/api/com/sun/tools/example/trace/package-index.html 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. 它向您展示了如何使用事件,这确实会给您一个ThreadReference。 It also shows you how to start up the second JVM programmatically. 它还向您展示了如何以编程方式启动第二个JVM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM