我正在研究auto-value及其扩展名,即我的Android应用程序中的auto-value-parcelauto-value-parcel-adapter

我有这些模型课:

@AutoValue
public abstract class Xenarchaeota implements Parcelable {

    @ParcelAdapter(AmoebaTypeAdapter.class)
    public abstract Set<Amoeba> amoebas();

    public static Builder builder() {
        return new AutoValue_Xenarchaeota.Builder();
    }

    @AutoValue.Builder
    public abstract static class Builder {

        public abstract Builder setAmoebas(Set<Amoeba> value);

        public abstract Xenarchaeota build();
    }
}


@AutoValue
public abstract class Amoeba implements Parcelable {

    public abstract String surname();

    public static Builder builder() {
        return new AutoValue_Amoeba.Builder();
    }

    @AutoValue.Builder
    public abstract static class Builder {

        public abstract Builder surname(final String value);

        public abstract Amoeba build();
    }

}

我的类型适配器是我出现问题的地方
class AmoebaTypeAdapter implements TypeAdapter<Set<Amoeba>> {

    @Override
    public Set<Amoeba> fromParcel(Parcel in) {
        final ArrayList<Amoeba> arrayList = new ArrayList<>();
        in.readTypedList(arrayList, Amoeba.CREATOR); // How to access the CREATOR?
        return new TreeSet<>(arrayList);
    }

    @Override
    public void toParcel(Set<Amoeba> value, Parcel dest) {
        final ArrayList<Amoeba> arrayList = new ArrayList<>(value);
        dest.writeTypedList(arrayList);
    }
}

我需要传递给readTypedArray的创建者在AutoValue_Amoeba中声明。

我的错误在哪里?对auto-value-parcel的误解?

最佳答案

AutoValue:宗地扩展无法处理集,但是如果将属性转换为List,则无需自定义适配器即可直接使用。如果要将其视为Set,可以执行此操作。请记住,您可能还需要缓存Set

@AutoValue
public abstract class Xenarchaeota implements Parcelable {

    abstract List<Amoeba> amoebaList();
    public Set<Amoeba> amoebas() {
        return new TreeSet(amoebaList());
    }

    public static Builder builder() {
        return new AutoValue_Xenarchaeota.Builder();
    }

    @AutoValue.Builder
    public abstract static class Builder {

        public abstract Builder setAmoebas(Set<Amoeba> value);

        public abstract Xenarchaeota build();
    }
}

10-08 03:25