安卓中的可打包和继承

我得到了一个Parcellable的实现,用于不涉及继承的单个类。在继承方面,我无法找出实现接口的最佳方法。假设我得到了这个:

public abstract class A {
    private int a;
    protected A(int a) { this.a = a; }
}

public class B extends A {
    private int b;
    public B(int a, int b) { super(a); this.b = b; }
}

问题是,为 B(在 A 中?在两个中)实现 Parcelable 接口的推荐方法是什么?如何实现?


答案 1

这是我最好的解决方案,我很乐意听到有人对此有所思考。

public abstract class A implements Parcelable {
    private int a;

    protected A(int a) {
        this.a = a;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(a);
    }

    protected A(Parcel in) {
        a = in.readInt();
    }
}

public class B extends A {
    private int b;

    public B(int a, int b) {
        super(a);
        this.b = b;
    }

    public static final Parcelable.Creator<B> CREATOR = new Parcelable.Creator<B>() {
        public B createFromParcel(Parcel in) {
            return new B(in);
        }

        public B[] newArray(int size) {
            return new B[size];
        }
    };

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(b);
    }

    private B(Parcel in) {
        super(in);
        b = in.readInt();
    }
}

答案 2

这是我的变体。我认为这很好,因为它非常清楚地显示了虚拟读写方法之间的对称性。

附注:我认为谷歌在设计可 Parcelable 界面方面做得非常糟糕。

public abstract class A implements Parcelable {
    private int a;

    protected A(int a) {
        this.a = a;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(a);
    }

    public void readFromParcel(Parcel in) {
        a = in.readInt();
    }
}

public class B extends A {
    private int b;

    public B(int a, int b) {
        super(a);
        this.b = b;
    }

    public static final Parcelable.Creator<B> CREATOR = new Parcelable.Creator<B>() {
        public B createFromParcel(Parcel in) {
            return new B(in);
        }

        public B[] newArray(int size) {
            return new B[size];
        }
    };

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(b);
    }

    public void readFromParcel(Parcel in) {
        super(in);
        b = in.readInt();
    }
}

推荐