Construct a new Object() with the toString result of another Object

196 Views Asked by At

I was wondering if it was possible to get some String value of an Object to access that Object on the same machine (same RAM) or the same VM via that particular String.

e.g.

Object objA1 = new Object();
System.out.print(objA1.adress); => output: d146a6581ed9e
Object objExt = Object.buildFromMemoryAdress("d146a6581ed9e");

I hope you understand what I'm trying to understand.

EDIT: I found in

http://javapapers.com/core-java/address-of-a-java-object/#&slider1=1

a Class that allows me to get the String of the logical address of an instance on the (VM?) memory: sun.misc.Unsafe

I think I can also use Unsafe to retrieve an Object from the (restricted to the VM?) memory.

If not possible like this, how would I do it, and since it's out of curiosity are there any other languages (especially high end) that allow direct memory access like this?

3

There are 3 best solutions below

4
On

Absolutely not. In fact, it's clearly impossible, given that you can obviously have two different objects whose toString() methods return the same string. As a simple example:

Integer a = new Integer(10);
Integer b = new Integer(10);

Object x = Object.buildFromToString("10");

What should x refer to? The same object that a refers to, or the same object that b refers to?

toString() is not meant to return an object identifier - it's just meant to return some sort of textual representation of an object. Just because the default implementation returns something which looks a bit like an identifier shouldn't be taken as an indication that it should be used as an identifier.

If you want to store some way of accessing an object at some other point in time, I suggest you just store a reference to it as an Object variable.

0
On

No, this is not possible. Java objects are only accessible if you have a reference to those objects. What you can do is store your objects in a Map<String, Object> under a given name, and get back the reference of the object from its name, using the map.

2
On

It is incorrect to assume that the number that you see in the toString() result is the memory address.

It is, in fact, the object's hash code. If the object isn't modified, its hash code remains constant. However, its memory address can change at any time: a compacting garbage collector can decide to move the object in memory whenever it feels like it.