Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
Tom Avatar asked Feb 21 '11 15:02

Tom


People also ask

How do you find the instance of a class using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.

How do you find the class object of associated class using reflection?

8. How to get the class object of associated class using Reflection? Explanation: forName(String className) returns the Class object associated with the class or interface with the given string name.

What is getClass () getName () in Java?

Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.

How do you check if an object is an instance of a class Java?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.


2 Answers

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

like image 123
Jon Skeet Avatar answered Oct 12 '22 03:10

Jon Skeet


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.
like image 21
Rich Avatar answered Oct 12 '22 02:10

Rich