我如何将这个通用类转换为Parcelable?

时间:2018-01-24 16:11:04

标签: java android parcelable

我想将此泛型类转换为可分配的对象,但我不清楚该问题的概念。

类别:

public class Type<T> implements Parcelable {

    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }

    public T get() { return t; }

}

这就是我尝试过的。但我知道这不正确,或者说这不完整。

public class Type<T> implements Parcelable {

    // T stands for "Type"
    private T t;

    protected Type(Parcel in) {
    }

    public void set(T t) { this.t = t; }

    public T get() { return t; }

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

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

    public static final Creator< Type > CREATOR = new Creator< Type >() {
        @Override
        public Type createFromParcel(Parcel in) {
            return new Type(in);
        }

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

}

2 个答案:

答案 0 :(得分:1)

您的通用数据类型可能会导致运行时错误

因此请确保您实现了Parcelable,并且您传递的类应该实现Parcelable,否则会导致运行时错误。

     public class Type<T extends Parcelable> implements Parcelable {

    // T stands for "Type"
    private T t;

    public void set(T t) { this.t = t; }

    public T get() { return t; }


    protected Type(Parcel in) {
        final String className = in.readString();
        try {
            t = in.readParcelable(Class.forName(className).getClassLoader());
        } catch (ClassNotFoundException e) {
            Log.e("readParcelable", className, e);
        }
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeValue(t);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Type> CREATOR = new Parcelable.Creator<Type>() {
        @Override
        public Type createFromParcel(Parcel in) {
            return new Type(in);
        }

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

答案 1 :(得分:1)

这与vikas kumar类似,但保证只能将Parcelable作为T参数传递,以避免异常。

public class Type<T extends Parcelable> implements Parcelable {
    private T t;

    protected Type(Parcel in) {
        t = (T) in.readValue(t.getClass().getClassLoader());
    }

    public static final Creator<Type> CREATOR = new Creator<Type>() {
        @Override
        public Type createFromParcel(Parcel in) {
            return new Type(in);
        }

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

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeValue(t);
    }
}