Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an object from its address

This is just for general knowledge and I am pretty sure it may not be possible, but I am curious to know.

Suppose I have a Student class object s1 and I pass it to a function as myFunc(s1.toString()). I haven't overrided toString() function. When the parameter will reach to the function, can I reference back to the original object just by it's address?

code:

public static void main(){
    Student s1;
    myFunc(s1.toString());
}
public static myFunc(String address){
    Student s2;
    s2 = //get s1 object from address string
}
like image 942
Mohd Naved Avatar asked May 09 '18 05:05

Mohd Naved


People also ask

Can I get a Python object from its memory address?

Now that we have addresses, we can get value/python objects again from the memory address using ctypes module. where, memeory_address is the memory address of the variable. value is the method which is used to extract a value.

How do I find the address of an object?

We can get an address using the id() function. id() function gives the address of the particular object. where the object is the data variables.

What is __ repr __ in Python?

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

How do you print the address of an object in Python?

Method 1: Find and Print Address of Variable using id() We can get an address using id() function, id() function gives the address of the particular object.


2 Answers

What you are asking to do is impossible by design while staying within the Java language. In contrast to languages like C that simply hand over arbitrary control over a region of memory to a program, the JVM uses a capability model, where both security and some measure of correctness depend on the fact that references can't be forged (manufactured from user-defined data such as a string instead of generated by the VM itself)--the only official way to get a reference to an object is to create that object via new or to copy an existing reference.

like image 169
chrylis -cautiouslyoptimistic- Avatar answered Oct 17 '22 09:10

chrylis -cautiouslyoptimistic-


While the default hashcode in the common implementations does use the object address to generate it, it's not reversible (and the address being used is an implementation detail, not a specified functionality).

Even if it were possible, the address of an object can change during the runtime (whereas the default hashcode doesn't), so it wouldn't be a viable approach even if there were a way to reverse it.

like image 41
Kayaman Avatar answered Oct 17 '22 08:10

Kayaman