4

Is it possible to get the address of a Java object in a JNI method? Or by any other method.

If it is not possible to get real address of an object, then is there a way to determine the memory layout of a data structure?


(This is just an example, description of my question is above this line.)

For instance, I have an array(or any other kinds of container, e.g. ArrayList, LinkedList etc.) of "objects", I want to know how these "objects" (not the references within the container) are allocated on the heap, they may not be allocated continuously, or even randomly ordered. So can I get any information about that?


Edit: Here is another thought, is there any other Java virtual machine can handle this kind of low level thing? For example, Jikes, or even Dalvik.

dawnstar
  • 507
  • 5
  • 10
  • Arrays are allocated contiguously. It's required by the [JVM Specification](http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.anewarray). Not a real question. – user207421 May 05 '13 at 10:03
  • Objects are references right? What if I assign each element within an array with newly newed objects with arbitrary order? Besides, array is just an example, what if I use a ArrayList or LinkedList. – dawnstar May 05 '13 at 13:03
  • "What if" still makes it a too ambiguous question. – Jesse May 05 '13 at 15:24
  • The question is *not* ambiguous - to someone who understands JNI, it's quite clear. – Chris Stratton May 05 '13 at 15:48
  • @dawnstar Arrays are still allocated contiguously. The objects referred to by the array elements aren't. Your purpose remains obscure. – user207421 May 05 '13 at 21:59
  • 2
    @EJP I think my purpose is clear, I want to get the memory layout of these "objects" of an array of "objects". Like you said, their references may allocated contiguously, but I want to know how the objects allocated on the heap. – dawnstar May 05 '13 at 23:42
  • @Jesse Forget about the "what if", those are only explanations to let people understand easily. My question is simply and easy, as in the topic. – dawnstar May 05 '13 at 23:45

1 Answers1

1

You can try http://javasourcecode.org/html/open-source/jdk/jdk-6u23/sun/misc/Unsafe.java.html. It provides some low-level operations

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 2
    http://stackoverflow.com/questions/7060215/how-can-i-get-the-memory-location-of-a-object-in-java - This may help with using `Unsafe` for this purpose. – prunge May 06 '13 at 03:09
  • @prunge This actually can do the trick, but every time I compile it, the warning says that "the Unsafe may be removed in the future" is really disturbing. Any way, this seems to be the only way to do the trick without touching the source code in the OpenJDK. – dawnstar May 11 '13 at 12:19