Java: How to store and retrieve memory address lik

2019-06-27 13:25发布

I come from a C++ background. In C++ I can store a memory adress which I just new'd in a global array and re-use it later. For example, say I have two classes X, Y and I create two objects x, y. The global array StoreAddresses[2] is defined as:

 uint32_t StoreAddresses[2];

I write:

 X * x = new X();
 Y * y = new Y();
 StoreAdresses[0] = (uint32t *) x; //for example, 0x12345678
 StoreAdresses[1] = (uint32t *) y; //for example, 0x12345698

Anywhere in my program, I can retrieve the data written in memory by calling:

 X * stored_x = (X*)StoreAdresses[0];
 Y * stored_y = (Y*)StoreAdresses[1];

How can I accomplish that in Java? Appreciate the help!

4条回答
劫难
2楼-- · 2019-06-27 13:45

In java, you can use object references. There aren't void or integral pointers, but since every object inherits from Object, you can use cast Object references instead

import java.lang.*;

class test {

    static Object[] StoreObjectRefs = new Object[2];

    public static void main(String args[])
    {
        Integer x = new Integer(1);
        Float y = new Float(2.0);

        StoreObjectRefs[0] = (Object) x;
        StoreObjectRefs[1] = (Object) y;

        System.out.println((Integer)StoreObjectRefs[0]+(Float)StoreObjectRefs[1]);
    }

}

Be careful though, references are passed by value in functions.

查看更多
Summer. ? 凉城
3楼-- · 2019-06-27 13:48

Ya. You can accomplish this in Java. But ,for manipulating address , C++ is is obviously a better choice. Java does not provide that facility to manipulate an address easily for security reason.

If you call the hashCode() on any object , it will return the string representation of the address of any object .

查看更多
【Aperson】
4楼-- · 2019-06-27 13:53

You can do this in Java using Unsafe. However its a very bad idea. That is because address of an object can change at any time (by a GC) If you store the address like this an use it later it might not be valid any more and even crash your application. If the GC believes an object does not have a strong reference, it may clean up the object. When you try to reference the object again, it may not be in the JVM any more.

The size of an address can change depending on how you start the JVM. A 64-bit JVM usually uses 32-bit references (which might a surprise coming from C++) You can get this with Unsafe.ADDRESS_SIZE

I would only use Unsafe to see what the addresses are to see how the objects are laid out in your cache. (Which is not very useful as there is not much you can about it :( )

It is likely that what ever you are trying to can be done a better way. Can you give us more details?

查看更多
三岁会撩人
5楼-- · 2019-06-27 13:53

What Peter said is correct. I would add that you need to start thinking in java terms, not in C++ terms.

It might help you to know that in Java X x = new X(); is almost entirely equivalent to what in C++ is X* x = new X();

查看更多
登录 后发表回答