As explained in the other answers you can do it by using the JDI protocol. It is rather simple: you need to run the JVM in debug mode using
--agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=56855
after that, you can connect to the remote (or local JVM) and list all instances of the specified class. Also, you cannot directly cast remote objects to the real object but you can access to all the fields of the remote object and even cal methods.
Here how you can connect to remote JVM and get VirtualMachine.
private static VirtualMachine attach(String hostname, String port) throws IOException, IllegalConnectorArgumentsException {
//getSocketAttaching connector to connect to other JVM using Socket
AttachingConnector connector = Bootstrap.virtualMachineManager().attachingConnectors()
.stream().filter(p -> p.transport().name().contains("socket"))
.findFirst().get();
//set the arguments for the connector
Map<String, Argument> arg = connector.defaultArguments();
arg.get("hostname").setValue(hostname);
arg.get("port").setValue(port);
//connect to remote process by socket
return connector.attach(arg);
}
After getting VirtualMachine you can get instances of a class using methods classesByName and instances. It return List of ReferenceType:
VirtualMachine vm = attach("localhost", "56856");
//get all classes of java.lang.String. There would be only one element.
List<ReferenceType> classes = vm.classesByName("java.lang.String");
//get all instances of a classes (set maximum count of instannces to get).
List<ObjectReference> o = classes.get(0).instances(100000);
//objectReference holds referenct to remote object.
for (ObjectReference objectReference : o) {
try {
//show text representation of remote object
System.out.println(objectReference.toString());
} catch (com.sun.jdi.ObjectCollectedException e) {
//the specified object has been garbage collected
//to avoid this use vm.suspend() vm.resume()
System.out.println(e);
}
}
Here is a working example of a program than runs and connects to itself and list all instances of a java.lang.String. To run an example you need tool.jar from jdk in you classpath.