這是一個通用的JAVA問題。在Android中,有一個接口Parcelable
:具有約束訪問問題的泛型類
這是official documentation裏面的例子:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
我們實現兩個功能describeContents()
和writeToParcel
需要。
(問題) 除了它們之外,我們還需要實現Parcelable.Creator<T>
接口作爲一個名爲CREATOR靜態字段。
一切實際上很簡單。現在我想創建一個具有Parcelable類類型泛型類:
public class ShushContainer<T extends Parcelable> implements Parcelable
我能夠實現Parcelable。我可以撥打T
的writeToParcel
功能。但是,我無法訪問靜態CREATOR字段。
public class ShushContainer<T extends Parcelable> implements Parcelable {
Vector<T> items;
String someField;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(someField);
dest.writeInt(items.size());
for(int i=0;i<items.size();i++)
items.get(i).writeToParcel(dest, flags);
}
public ShushContainer(Parcel in) {
someField = in.readString();
int size = in.readInt();
for(int i=0;i<size;i++)
//this does not work
items.add(T.CREATOR.createFromParcel(in));
}
public static final Parcelable.Creator<ShushContainer> CREATOR = new Parcelable.Creator<ShushContainer>() {
public ShushContainer createFromParcel(Parcel in) {
return new ShushContainer(in);
}
public ShushContainer[] newArray(int size) {
return new ShushContainer[size];
}
};
}
T是實現Parcelable的另一個類。 –
那麼該類如何具有'CREATOR',因爲它是在ShushContainer中定義的。這個變量只屬於這個類。簡單地使用它爲什麼你需要T.CREATOR只需使用CREATOR –
Nopes ShushContainer實現Parcelable並擁有自己的CREATOR。 T還實現了Parcelable並擁有自己的CREATOR。正是這個創作者,我無法訪問。 –