The fifth way!
Use the heapViewer demo JVM TI agent shipped with JDK.
java -agentpath:%JAVA_HOME%\\demo\\jvmti\\heapViewer\\lib\\heapViewer.dll MainClass
java -agentpath:$JAVA_HOME/demo/jvmti/heapViewer/lib/libheapViewer.so MainClass
You can look at the source code of this heapViewer agent under $JAVA_HOME/demo/jvmti/heapViewer/src directory. If you want to learn about JVM TI agents, you may want to read Kelly's blog on agents.