简体   繁体   English

将 GSON 用于通用 Parcelable——如何检索类类型

[英]Using GSON for generic Parcelable -- how to retrieve class type

Caveat警告

There may be an easier / smarter way to do this.可能有一种更简单/更智能的方法来做到这一点。 I'm not a good Android developer.我不是一个好的 Android 开发者。 Please advise请指教

Problem问题

I have a library with about 100 different models.我有一个包含大约 100 个不同模型的库。 I now have to make all of these models parcelable.我现在必须使所有这些模型都可以打包。

Rather than implement writeToParcel for every single one , I thought it would be nice if I could just create a super class that used generic serialization logic. writeToParcel每一个都实现writeToParcel ,我认为如果我能创建一个使用通用序列化逻辑的超类就好了。 Something like the following:类似于以下内容:

public abstract class Model implements Parcelable
{

    public final static Parcelable.Creator<Model> CREATOR = new Parcelable.Creator<Model>() {
        @Override
        public Model createFromParcel ( Parcel parcel )
        {
            Gson gson = new Gson();
            String type = parcel.readString();
            String serialized = parcel.readString();
            gson.fromJson(serialized, /* HELP ME */)
        }

        @Override
        public Model[] newArray ( int i )
        {
            // TODO: I haven't even read the docs on this method yet
        }
    };

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

    @Override
    public void writeToParcel ( Parcel parcel, int i )
    {
        Gson gson = new Gson();
        String type = this.getClass().getName();
        String serialized = gson.toJson(this);
        parcel.writeString(type);
        parcel.writeString(serialized);
    }

}

Then in each of my models I just say:然后在我的每个模型中我只是说:

public class Whatever extends Model {

The problem is that Gson requires me to provide Type in order to de-serialize.问题是 Gson 要求我提供Type以进行反序列化。 How can I get this Type value?我怎样才能得到这个Type值? As you can see, I tried using this.getClass().getName() to get the name of the class, but I have no idea how to reverse this and go from a string back to a type.如您所见,我尝试使用this.getClass().getName()来获取类的名称,但我不知道如何将其反转并将其从字符串返回到类型。 I also don't fully understand the difference between Class<T> and Type .我也不完全理解Class<T>Type之间的区别。

I solved this by using:我通过使用解决了这个问题:

String type = this.getClass().getCanonicalName();

to get the type, and then:获取类型,然后:

return (Model) gson.fromJson(serialized, Class.forName(type));

in my createFromParcel method在我的createFromParcel方法中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM