所以,我有以下类,我想使用 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
}
我知道类变量的训练。但是在内部类(class)的 final 和 final 中遇到麻烦。
做了一些额外的研究,我研究了 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 实现中完全忽略了所有那些 final/常量。
这让我有点困惑,所以研究了 Java Serialize finals 并在堆栈溢出时发现了这个 discussion。我从他们那里了解到,它是由 JVM 使用反射完成的。然后我查看了 Parcel 和 Parcelable 的来源,似乎没有任何地方 final 是明确处理的。
我必须还是不必?我到底错过了什么?
最佳答案
Seems like these guys are completely ignoring all those finals/Constants from their Parcelable implementation.
好吧,如果你看看 source对于 BluetoothDevice
,您会注意到所有 final
变量都是在构造函数之外定义的。因此,当 return new BluetoothDevice(in.readString())
被调用时,所有 final
变量都被初始化为它们各自的值,然后调用构造函数 BluetoothDevice(String address)
。
我想说的是,这些值不是从 Parcel
写入或读取的。它们只是在 Parent
的 CREATOR
调用构造函数之前由类初始化(尽管您尚未在问题的 Parent
源代码)。
现在,假设您根据参数化构造函数中的参数初始化 final
变量的值。例如,
public Parent(int x, Animal y, String z) {
this.x = x;
this.y = y;
this.z = z;
}
在这种情况下,您需要将x
、y
和z
写入
就像处理任何 writeToParcel()
中的 Parcelnon-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
几乎一样。我不认为它们是什么有什么区别。
关于java - Android Parcelable final ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25313714/