Tom
Tom

Reputation: 8127

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

Upvotes: 19

Views: 15356

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533510

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.

Upvotes: 3

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

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.

Upvotes: 1

Stephen C
Stephen C

Reputation: 718798

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.

Upvotes: 1

Rich
Rich

Reputation: 15767

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.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500525

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

Upvotes: 9

Related Questions