所以,我有下面的类,我想使用来序列化
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;
}
似乎这些家伙完全忽略了他们的可分割实现中的所有决赛/常量。
这让我有点困惑,所以研究了Java如何序列化决赛,并在堆栈溢出上发现了这个讨论。我从他们那里了解到,这是由JVM使用反射完成的。然后我查看了包裹和Parcelable的源代码,似乎没有哪个决赛是明确处理的。
我必须这么做,还是不必这样做?我到底错过了什么?
发布于 2014-08-15 13:55:43
似乎这些家伙完全忽略了他们的可分割实现中的所有决赛/常量。
如果您查看来源 for 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
写入writeToParcel()
中的Parcel
,就像编写任何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
一样。我不认为他们有什么区别。
https://stackoverflow.com/questions/25313714
复制相似问题