Parcable的通用数组

时间:2016-07-14 22:11:41

标签: android generics parcelable

我使用插件生成parcelable实现,这就是我得到的代码 我在Metrics(Parcel in)上有一个错误编译 它可能是因为通用数组。我该如何解决? 通用T可以包含String,Number或boolean only。

public class Metrics<T extends Parcelable> implements Parcelable {
    private T[] yData;

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeTypedArray(this.yData, flags);
    }

    public Metrics() {
    }

    protected Metrics(Parcel in) {
        this.yData = in.createTypedArray(T.CREATOR);
    }

    public static final Parcelable.Creator<Metrics> CREATOR = new Parcelable.Creator<Metrics>() {
        @Override
        public Metrics createFromParcel(Parcel source) {
            return new Metrics(source);
        }

        @Override
        public Metrics[] newArray(int size) {
            return new Metrics[size];
        }
    };
}

1 个答案:

答案 0 :(得分:0)

您可以使用List代替数组:

public class Metrics<T extends Parcelable> implements Parcelable {

    private List<T> yData;

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

        if (yData == null || yData.size() == 0)
            dest.writeInt(0);
        else {
            dest.writeInt(yData.size());
            final Class<?> objectsType = yData.get(0).getClass();
            dest.writeSerializable(objectsType);
            dest.writeList(yData);
        }
    }

    public Metrics() {
    }

    protected Metrics(Parcel in) {

        int size = in.readInt();
        if (size == 0) {
            yData = null;
        } else {
            Class<?> type = (Class<?>) in.readSerializable();
            yData = new ArrayList<>(size);
            in.readList(yData, type.getClassLoader());
        }
    }

    public static final Parcelable.Creator<Metrics> CREATOR = new Parcelable.Creator<Metrics>() {
        @Override
        public Metrics createFromParcel(Parcel source) {
            return new Metrics(source);
        }

        @Override
        public Metrics[] newArray(int size) {
            return new Metrics[size];
        }
    };
}