所以,我有以下类,我想使用Android Parcelable序列化
public class Parent{
public static final int x; //primtive type
public static final Animal y; //another percelable
public static final String z; //object type
public class Inner{
public static final int a; //primtive type
public static final Animal b; //another percelable
public static final String c; //object type
}
private int classIntState; //primtive type
private Animal classAnimalState; //another percelable
private String classObjectState; //object type
}
我知道类变量的练习。但是在内线类的决赛和决赛中遇到麻烦。
完成了一些额外的研究,我查看了BlutoothDevice类,它恰好也是Parcelable并且有一堆常量。
而且,我在源代码上找到了这个,
public static final Parcelable.Creator<BluetoothDevice> CREATOR =
new Parcelable.Creator<BluetoothDevice>() {
public BluetoothDevice createFromParcel(Parcel in) {
return new BluetoothDevice(in.readString());
}
public BluetoothDevice[] newArray(int size) {
return new BluetoothDevice[size];
}
};
public void writeToParcel(Parcel out, int flags) {
out.writeString(mAddress);
}
BluetoothDevice(String address) {
getService(); // ensures sService is initialized [nothing to do with parcelable]
if (!BluetoothAdapter.checkBluetoothAddress(address)) {
throw new IllegalArgumentException(address + " is not a valid Bluetooth address");
}
mAddress = address;
}
似乎这些家伙完全无视Parcelable实施中的所有决赛/常数。
这让我有点困惑,所以看看Java Serialize如何在堆栈溢出时发现这个discussion。我从他们的理解是,它是由JVM使用反射完成的。然后我查看了Parcel和Parcelable来源,似乎没有任何明确的句柄处理。
我必须,或者我不需要?我真的想念的是什么?
答案 0 :(得分:1)
似乎这些家伙完全无视Parcelable实施中的所有决赛/常数。
好吧,如果您查看BluetoothDevice
的{{3}},您会注意到所有final
变量都是在构造函数之外定义的。因此,当调用return new BluetoothDevice(in.readString())
时,构造函数定义中的所有final
变量 初始化为其各自的值,然后调用构造函数BluetoothDevice(String address)
。
我想说的是,这些值不是从Parcel
写入或读取的。它们只是在CREATOR
Parent
调用构造函数之前由类初始化(尽管您没有在问题的Parent
源代码中定义一个)。
现在,假设您根据参数化构造函数中的参数初始化final
变量的值。例如,
public Parent(int x, Animal y, String z) {
this.x = x;
this.y = y;
this.z = z;
}
在这种情况下,您需要将x
,y
和z
写入Parcel
中的writeToParcel()
和任何non-final
值一样。
然后在Parent
班级CREATOR
:
public static final Parcelable.Creator<Parent> CREATOR =
new Parcelable.Creator<Parent>() {
public Parent createFromParcel(Parcel in) {
//read values from Parcel
int intParam = in.readInt();
Animal animalParam = in.readParcelable(Animal.class.getClassLoader());
String stringParam = in.readString();
//create parent
Parent parent = new Parent(intParam, animalParam, stringParam);
return parent;
}
public Parent[] newArray(int size) {
return new Parent[size];
}
};
也就是说,您读取变量的值,然后使用构造函数来分配它们。同样,这几乎与变量不是final
的情况几乎相同。我认为它们没有任何区别。