How to get the object instances of a Java class? This class that is not necessarily a singleton , not necessarily provide static methods , not necessarily managed by Spring , and even can not modify the source code of the case , how do we get all the object instances of this class ? Here is an implementation based on JVMTI.
Then call the function **InstancesOfClass.getInstances(Class<? > targetClass)** to get all object instances of a class.
```java public class InstancesOfClass { /** * native method : Returns all instances of a class. * @param targetClass need to query the instances of Class * @return */ public static native Object[] getInstances(Class<? > targetClass); }
Principle of implementation
Java does not have an interface to get instances based on class, you need to use the JVMTI interfaces IterateOverInstancesOfClass and GetObjectsWithTags.
First write a class that contains native methods
``java public class InstancesOfClass { /** * native method : returns all instance objects * @param targetClass The Class to query for instances. * @return */ public static native Object[] getInstances(Class<? > targetClass); }
// Convert jobject* to jobjectArray and return it. jobjectArray result = env->NewObjectArray(count, targetClazz, NULL); for (int i = 0; i < count; i++) { env->SetObjectArrayElement(result, i, instances[i]); } }
Then compile the cpp source code with gcc/g++, generate the corresponding dynamic link libraries .so, .dylib and .dll under linux/mac/windows, load the corresponding local link libraries through System.load(), and finally call InstancesOfClass.getInstances(Class). <? > targetClass) method.