开发者

Java Reflection: get instances of a given class found by entering its name?

Is it possible to get all instances of a class by entering this class's name as a string?

Something like this?

var instances = Reflection.findClass("com.someone.MyClass").getInstances();

Any 开发者_JS百科feedback is appreciated. Thanks.


No, there's nothing like that available. If you hook into the debugging API you may be able to do it, but not when running "normally".


I don't know of a way of doing this at runtime, but, if you are happy doing it 'offline', you can do the following:

  1. Take a heap dump
  2. Load the heap dump into Eclipse MAT
  3. Open an OQL pane, and enter a command such as select * from com.someone.MyClass. Running this query will return the instances in memory at the time that the heap dump was taken.


This is the sort of thing profilers are good for. With YourKit you can search for instances based on wildcarded class and inspect/navigate into them from largest to smallest or some other sort criteria.


This answer provides some options using various instrumentation APIs. But these generally work on an application running in a separate JVM, and they entail stopping the JVM and trawling through all objects in the heap to find relevant instances.


A JVM does not keep any internal collections of all instances of each class. But you can do this kind of thing yourself ... if you implement the behavior in each specific class or classes that you are interested in. You just need to be careful to avoid creating a memory leak by keeping references to instances that would otherwise be collectible garbage.


The problem here is not finding the class object (this can be done by Class.forName()), but that normally a class does not have any knowledge of its instances.

If you have control over your class, you could create a registry of all instances, and add each instance to this in the constructor. But you should be careful to not disable garbage collection by this, so use weak references instead of normal ones.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜