views:

146

answers:

3

Forgive me if this is an ignorant question, I'm not exactly an expert programmer just curious. Is it possible to read the working memory, say for an instance of a class, from inside a running program?

I know you can do something like println(theInstance.getClass()); and it will give you the memory address of the instance (I'm assuming thats what it is). I'm wondering if can do something like byte[]memory = theInstance.getClass().getMemory(); println(toString(memory)); I know thats all made up but just to illustrate.

+2  A: 

No, printing the result of getClass() doesn't give a "memory address"; it gives a string representation of a class (which would be something like "class Argyle").

It's not clear, from your question, what you'd expect the contents of such a thing to be. If you'd like to understand how Java represents objects in memory, then read the VM specification. Then again, the Java virtual machine does not mandate any particular internal structure for objects.

Jonathan Feinberg
+3  A: 

Not using standard Java APIs. However, you can access memory through sun.misc.Unsafe (you will probably need to use reflection to get the instance of this class). You can, of course, also do this through JNI.

But why would you want to?

Tom Hawtin - tackline
@Tom - actually, I don't think that JNI does allow you to get at the raw memory per se. Rather, it provides methods for getting and setting (for example) an object's fields. (If you knew what the internal representation of a JNI FieldID was, maybe you could "punch" through the abstraction barrier ...)
Stephen C
It's C. The abstraction barriers are not very robust...
Tom Hawtin - tackline
A: 

I haven't looked at this lately but if on Linux you could seek/read /proc/PID/mem.

Xepoch