是否有一种简单的方法可以在Java中获取特定类的所有对象实例

问题描述:

目前我正在使用Java代理来汇编内存统计信息。在仪器的帮助下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

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包含几个示例,所以我'我相信它是可行的。

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.