我正在尝试创建 public class MyClass<T extends Parcelable> implements Parcelable
.我在执行 Parcelable
时遇到问题.是否可以创建一个实现 Parcelable
的通用类? (请注意 T
是有界的,因此它也必须实现 Parcelable
)。
我遇到了麻烦,因为 Parcelable 接口(interface)需要一个static 变量:public static final Parcelable.Creator<MyParcelable> CREATOR
.因此我不能做 public static final Parcelable.Creator<MyClass<T>> CREATOR
因为MyParcelable<T>
是非静态的。
安德烈
最佳答案
我在使用泛型的类上实现 Parcelable 时遇到了类似的问题,第一个问题与您遇到的问题相同:
Thus I cannot do public static final Parcelable.Creator> CREATOR because MyParcelable is nonstatic.
第二个是读取一个 Parcelable 对象,您需要访问 ClassLoader
,由于 type erasure 而无法从 T
获取该对象.
下面的类(class)改编 self 在生产中使用的类(class),它克服了这两个问题。 注意:我没有专门测试过这个类,所以如果您有任何问题,请告诉我。
public class TestModel<T extends Parcelable> implements Parcelable {
private List<T> items;
private String someField;
public List<T> items() {
return items;
}
public void setItems(List<T> newValue) {
items = newValue;
}
public String someField() {
return someField;
}
public void setSomeField(String newValue) {
someField = newValue;
}
//region: Parcelable implementation
public TestModel(Parcel in) {
someField = in.readString();
int size = in.readInt();
if (size == 0) {
items = null;
}
else {
Class<?> type = (Class<?>) in.readSerializable();
items = new ArrayList<>(size);
in.readList(items, type.getClassLoader());
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(someField);
if (items == null || items.size() == 0)
dest.writeInt(0);
else {
dest.writeInt(items.size());
final Class<?> objectsType = items.get(0).getClass();
dest.writeSerializable(objectsType);
dest.writeList(items);
}
}
public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
public TestModel createFromParcel(Parcel in) {
return new TestModel(in);
}
public TestModel[] newArray(int size) {
return new TestModel[size];
}
};
//endregion
}
关于java - 是否可以打包通用类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18797399/