将 GSON 用于通用 Parcelable——如何检索 class 类型
Using GSON for generic Parcelable -- how to retrieve class type
警告
可能有更简单/更聪明的方法来做到这一点。我不是一个好的 Android 开发人员。请指教
问题
我有一个图书馆,里面有大约 100 个不同的模型。我现在必须让所有这些模型都可以打包。
而不是为每个实施writeToParcel
,我认为如果我能创建一个使用通用序列化逻辑的 super class。类似于以下内容:
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);
}
}
然后在我的每个模型中我只说:
public class Whatever extends Model {
问题是 Gson 需要我提供 Type
才能反序列化。我怎样才能得到这个 Type
值?如您所见,我尝试使用 this.getClass().getName()
来获取 class 的 name,但我不知道如何反转它并从字符串变回类型。我也不完全理解 Class<T>
和 Type
之间的区别。
我使用以下方法解决了这个问题:
String type = this.getClass().getCanonicalName();
获取类型,然后:
return (Model) gson.fromJson(serialized, Class.forName(type));
在我的createFromParcel
方法中
警告
可能有更简单/更聪明的方法来做到这一点。我不是一个好的 Android 开发人员。请指教
问题
我有一个图书馆,里面有大约 100 个不同的模型。我现在必须让所有这些模型都可以打包。
而不是为每个实施writeToParcel
,我认为如果我能创建一个使用通用序列化逻辑的 super class。类似于以下内容:
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);
}
}
然后在我的每个模型中我只说:
public class Whatever extends Model {
问题是 Gson 需要我提供 Type
才能反序列化。我怎样才能得到这个 Type
值?如您所见,我尝试使用 this.getClass().getName()
来获取 class 的 name,但我不知道如何反转它并从字符串变回类型。我也不完全理解 Class<T>
和 Type
之间的区别。
我使用以下方法解决了这个问题:
String type = this.getClass().getCanonicalName();
获取类型,然后:
return (Model) gson.fromJson(serialized, Class.forName(type));
在我的createFromParcel
方法中