Java 访问局部变量名
我目前正在编写一个程序,我想在程序执行期间访问局部变量的变量名并将它们传递到外部。我知道 Java 会在编译期间转储局部变量名称,除非在调试模式下编译。
环顾四周后,似乎 JDI/JPDA 是此类工作的最佳选择。假设 ref 引用 ThreadReference ,以下是我到目前为止所得到的:
ref.suspend();
StackFrame currentFrame = ref.frame(0);
List<LocalVariable> vars = currentFrame.visibleVariables();
ref.resume();
两个问题:
- 我走在正确的轨道上,还是有更好的方法来做到这一点?
- 如何获取
ThreadReference
并将其设置为ref
? LocatableEvent 似乎是我所需要的,但是任何人都可以提供如何使用它的示例吗?
非常感谢!
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:
- Am I on the right track, or is there a better way to do this?
- How do I acquire the
ThreadReference
to set toref
? LocatableEvent seems to be what I need, but can anyone provide an example on how to use it?
Many thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有多少人有这方面的经验。
到别处寻找答案。我有代码链接,但现在没有了。无法删除此答案,因为它已被接受。
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.
是的,您走在正确的道路上!
对于任何想要尝试开始使用 JDI 的人来说,“Trace”示例非常宝贵:
http://www.docjar.com/docs/api/com/sun/tools/example/trace/package-index.html
这是一个可用的主干。它向您展示了如何使用事件,这确实会给您一个 ThreadReference。它还向您展示了如何以编程方式启动第二个 JVM。
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.