简体   繁体   中英

Why can I not pass reference address as opposed to Parcel/Serial Object?

According to the StackOverflow and the internet the way to pass an object is to either serialize or parcelize (or use "static" - frowned upon).

I would like to know why I can not pass the address

     MainActivity.toString();  // MainActivity@b0ff5f80

Then while in the new class/Activity simply change the adress of the newly created object ?

MainActivity originalMainActivity = new MainActity();
originalMainActivity = getIntent.getStringExtra("originalMainActivity");
//yes I realize the above line is incompatible....Obj != String 

if the object has already been created and is sitting in the heap (I think ??) Why can we not reassign address ? If we can can someone please provide an example ? Thank You.

ps (after all when we pass a class object in a Constructor are we not actually passing ref address) Thx again.

You seem to be thinking in terms of addresses, as if you were in C or in C++.

However:

  1. You are completely misunderstanding the purpose of toString : in the general case, the only valid use of toString is printing a representation of the object, for debugging purposes. There is nothing to say that that string can be used later to regenerate, or find the object again.

  2. The Java language does not give any way to access memory addresses, in part because the garbage collector is generally free to rearrange memory. The only way to work around that is to pin objects and operate outside of the Java language.

Besides, you should understand that when you get an object out of a Parcel , you are not necessarily in the same process (even if it is your process, your process may have been background-killed before being restarted) - so your method could only work in a restricted set of cases.

Then while in the new class\\Activity simply change the adress of the newly created object ?

Among other reasons, because that is not possible in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM