Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 573
sinekonata Avatar asked Nov 28 '25 16:11

sinekonata


2 Answers

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.

like image 67
NPE Avatar answered Nov 30 '25 06:11

NPE


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.

like image 24
Jon Skeet Avatar answered Nov 30 '25 06:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!