所以,我有以下课程,我想使用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实现中的所有那些finals / Constants。
这让我有些困惑,因此研究了Java序列化决赛的方式,并在堆栈溢出时找到了此讨论。我从他们那里了解到的是,它是由JVM使用反射完成的。然后,我查看了Parcel和Parcelable的源代码,似乎在任何地方都不明显地使用了final句柄。
我必须还是不需要?我在这里真的想念什么?
似乎这些家伙完全忽略了其Parcelable实现中的所有那些finals / Constants。
好吧,如果你看一下源为BluetoothDevice
,你会发现,所有的final
变量都在构造函数之外定义。因此,在return new BluetoothDevice(in.readString())
调用时,构造函数定义之外的所有final
变量都将初始化为它们各自的值,然后调用构造函数。BluetoothDevice(String address)
我要说的是,这些值不是从写入或读取的Parcel
。它们可以在CREATOR
of调用构造函数之前由类简单地初始化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];
}
};
也就是说,您读取变量的值,然后使用构造函数分配它们。同样,这几乎与变量not几乎相同final
。我认为它们之间没有任何区别。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句