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.
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.
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.
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.
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.
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:
select * from com.someone.MyClass
. Running this query will return the instances in memory at the time that the heap dump was taken.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With