是否有一种简单的方法可以在 Java 中获取特定类的所有对象实例
目前我正在开发一个 Java 代理来组装内存统计信息.借助 instrumentation API 我可以掌握这些类(并操纵它们).使用纯 Java,我可以估计每个对象使用的资源.到目前为止,一切顺利.
Currently I am working on a Java agent to assemble memory stats. With the help of the instrumentation API I can get a hold of the classes (and manipulate them). With plain Java I can get an estimate of the resources used for each object. So far, so good.
我现在面临的问题是如何获取特定类的每个 Object 实例".我可以进行字节码操作以获取对象实例,但我希望有另一个我不知道的 API,帮助我在没有如此繁重的侵入步骤的情况下完成我的目标.最后,应将性能影响降至最低.有什么想法吗?
The question I am faced with right now is "how to get a hold of every Object instance of a specific class". I can do byte code manipulation in order to get a hold of the object instance, but I was hoping there is another API I am not aware of, helping me to accomplish my goal without such a rather heavy intrusive step. At the end, the performance impact should be kept to a minimum. Any ideas?
推荐答案
Eclipse中的调试器可以向您展示一个类的所有实例,所以我查看了 Eclipse 的源代码.Eclipse 使用 Java Debug Wire Protocol,它允许您(从 Java 6 开始)查找所请求类的所有实例.如果您想走这条路,请获取 Eclipse 源代码的副本并查看 org.eclipse.jdi.internal.ReferenceTypeImpl
的 instances
方法.
The debugger in Eclipse can show you all the instances of a class, so I looked around Eclipse's sources. Eclipse uses the Java Debug Wire Protocol, which allows you (since Java 6) to look up all the instances of the requested class. If you want to go down this path, grab a copy of Eclipse sources and check out the instances
method of org.eclipse.jdi.internal.ReferenceTypeImpl
.
更简单的方法是使用 Java调试接口.注意 ReferenceType.instances
方法.
A simpler way is to use the Java Debug Interface. Note the ReferenceType.instances
method.
我还没有弄清楚如何使用 JDI 连接到正在运行的进程以及如何获取 ReferenceType
的实例.JDK 包含几个 examples,所以我我确定这是可行的.
I still haven't figured out how to use JDI to connect to a running process and how to obtain an instance of ReferenceType
. The JDK contains several examples, so I'm sure it's doable.
相关文章