【问题标题】:Type safety: The expression of type Xclass needs unchecked conversion to conform to Xclass<Yclass>类型安全:类型 Xclass 的表达式需要未经检查的转换才能符合 Xclass<Yclass>
【发布时间】:2013-08-21 20:57:58
【问题描述】:

如何解决这个问题? 类型安全:mResponseValue 类型的表达式需要未经检查的转换才能符合mResponseValue&lt;mUserStatus&gt;

mResponseValue<mUserStatus> ResponseValue = Mobile.JSONtoClass(responseService, mResponseValue.class);

public abstract class Mobile {

 public static String ObjToJson(Object obj)
 {    
     Gson gson = new Gson();
       return gson.toJson(obj);
 }

 public static <T> T JSONtoClass(String strRequest,Class<T> type)
 {
     Gson gson = new Gson();
     return gson.fromJson(strRequest, type);
 }  

}

【问题讨论】:

  • 使用通配符应该可以。

标签: java


【解决方案1】:

这个问题的根本原因是type erasure。当您调用Mobile.JSONtoClass(responseService, mResponseValue.class); 时,类型参数T 将被mResponseValue 替换,但是您将返回值分配给mResponseValue&lt;mUserStatus&gt;,这会导致未经检查的强制转换。

有问题的分配可以分为两部分:

    mResponseValue rawResponseValue = = Mobile.JSONtoClass(responseService, mResponseValue.class);    // OK
    mResponseValue<mUserStatus> parameterizedResponseValue  = rawResponseValue; // Warning: Type safety ...

因此,一个简单的解决方案是使用mResponseValue&lt;mUserStatus&gt;.class 作为JSONtoClass 调用的第二个参数,但是在运行时没有mResponseValue&lt;mUserStatus&gt;.class 这样的东西,因为类型参数被删除了。

为了规避这个问题,GSON 提供了接受java.lang.reflect.Type 的方法,该方法也保留了泛型类型信息。使用它们,警告可以消除如下:

public static <T> T JSONtoClass(String strRequest, java.lang.reflect.Type typeOfT)
{
    Gson gson = new Gson();
    return gson.fromJson(strRequest, typeOfT);
}

然后这样调用:

TypeToken<mResponseValue<mUserStatus>> typeToken = new TypeToken<mResponseValue<mUserStatus>>() {};
mResponseValue<mUserStatus> responseValue = Mobile.JSONtoClass(responseService, typeToken.getType());

此解决方案可防止编译器警告并实际上修复了可能由丢失类型信息引起的反序列化/序列化问题,请参阅 Serializing and Deserializing Generic Types 在 Gson 用户指南中了解更多信息。

【讨论】:

  • 虽然这是真的,但并没有说明他可以/应该做什么,这就是他所要求的......
  • Gson类型中的fromJson(String, Class)方法不适用于参数(String, Type)
  • @mirtiger 确保您使用的是java.lang.reflect.Type,我更新了我的答案以使用Type 的限定名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
相关资源
最近更新 更多