我正在调查自动值和它的扩展,即我的
Android应用程序中的auto-value-parcel和auto-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的CREATOR在AutoValue_Amoeba中声明.
解决方法
AutoValue:Parcel扩展无法处理集合,但如果将属性转换为List,则无需自定义适配器即可开箱即用.如果你想把它当成一个集合你就可以做到这一点.请记住,您可能还想缓存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(); } }