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