![](/img/trans.png)
[英]Java Compiler error puzzler: “inner classes cannot have static declarations” - except for simple types
[英]Android Parcelable Class - Inner classes cannot have static declarations
我一直在嘗試創建一個Android Parcelable對象,但始終遇到錯誤“內部類不能具有靜態聲明”。 作為參考,我一直在這里查看官方的Android教程。
我當前的代碼如下:
public class AppDetail implements Parcelable {
CharSequence label;
CharSequence name;
Drawable icon;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeArray(new Object[] { this.label, this.name, this.icon });
}
public static final Parcelable.Creator<AppDetail> CREATOR
= new Parcelable.Creator<AppDetail>() {
public AppDetail createFromParcel(Parcel in) {
return new AppDetail(in);
}
public AppDetail[] newArray(int size) {
return new AppDetail[size];
}
};
public AppDetail() {}
public AppDetail(Parcel in) {
Object[] data = in.readArray(AppDetail.class.getClassLoader());
this.label = (String)data[0];
this.name = (String)data[1];
this.icon = (Drawable)data[2];
}
}
我在網上找到其他人遇到類似問題,並得出結論,編譯器不喜歡靜態初始化程序塊(而不是靜態類本身)-我嘗試遵循此建議並聲明如下: public static Parcelable.Creator<AppDetail> CREATOR
在其他地方初始化-但是我遇到了同樣的錯誤。
我怎樣才能得到這個/可以編譯的東西?
是的,這很重要嗎?
是的,因為這就是您得到錯誤的原因。 您的錯誤不是由於Parcelable.Creator<AppDetail>
引起的,而是由於AppDetail
本身引起的。 內部類上不能有static
方法或數據成員,例如CREATOR
。
這樣做的凈結果是,直接實現Parcelable
類需要是static
內部類(即, public static class AppDetail implements Parcelable
)或常規(非內部)Java類。
基於此實現,僅使AppDetail
成為public static class
解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.