Does the readInt(), readFloat() etc. of Parcelable

2019-03-07 06:37发布

问题:

If your class implement parcelable then you know that you need a constructor for the system to construct your class based on the parcel it just received.

So a constructor usually like the one below will have to be written and this is where it gets a bit confusing:

public myClass(Parcel in){
   this.type = in.readInt();
   this.size = in.readInt();
}

You see, if there is a parameter and these read related methods are called like this:

   this.type = in.readInt(type);
   this.size = in.readInt(size);

Then it's all quite clear what's going on but instead, they don't have any parameters at all. So I'm wondering: is this how it is should be done? Are these method "smart" in some way that you don't have to tell them what field to get and they will always manage to get the right one?

Or is it sequential? If I use it like this:

   this.size = in.readInt();
   this.type = in.readInt();

The fields I'm about to get will all get messed up? If that's the case isn't this begging for bugs? I could be doing the wrong thing for a long time due to a careless mistake yet only to find it quite some time after?

回答1:

The order does matter. All writes must be read in the same order.

If that's the case isn't this begging for bugs? I could be doing the wrong thing for a long time due to a careless mistake yet only to find it quite some time after?

Indeed