Is it possible to use a Java agent to get the number of instances of any Java class? For example if we have
class Apple {
...
}
The Java agent will return how many Apple
instances are there in the JVM.
If it's not possible with a Java agent, is it possible to do it in another cross-platform manner - and without debug mode enabled (so JVMTI and JDI excluded)?
In order to count instances, you'll need to walk through the entire heap. Java Agents don't have such functionality. Basically, all they have is Instrumentation API.
The task is simple to do with JVM TI. There is IterateOverInstancesOfClass function which does almost what you want. JVM TI is not cross-platform, but you may create a JAR with dynamic libraries for the main supported platforms, and load the suitable one in runtime. That's how JNA works, for example.
The closest pure Java alternative is HotSpot diagnostic command to get a class histogram:
Among other things, it returns the number of instances of each class:
This is not a standard API though.