Java Reflection: get instances of a given class fo

2019-01-18 10:43发布

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 feedback is appreciated. Thanks.

5条回答
叛逆
2楼-- · 2019-01-18 10:52

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.

查看更多
仙女界的扛把子
3楼-- · 2019-01-18 11:01

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.
查看更多
Animai°情兽
4楼-- · 2019-01-18 11:05

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.

查看更多
Ridiculous、
5楼-- · 2019-01-18 11:14

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".

查看更多
冷血范
6楼-- · 2019-01-18 11:15

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.

查看更多
登录 后发表回答