类型安全:类型Xclass的表达式需要检查转换,以符合Xclass

[英]Type safety: The expression of type Xclass needs unchecked conversion to conform to Xclass


how to resolve this problem? Type safety: The expression of type mResponseValue needs unchecked conversion to conform to mResponseValue<mUserStatus>

如何解决这个问题?类型安全:类型mResponseValue的表达式需要未经检查的转换以符合mResponseValue

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);
 }  

}

}

1 个解决方案

#1


2  

The root cause of this problem is type erasure. When you call Mobile.JSONtoClass(responseService, mResponseValue.class); then the type parameter T will be substituted by mResponseValue, but you are assigning the return value to mResponseValue<mUserStatus> which results in an unchecked cast.

造成这个问题的根本原因是类型消除。当你叫移动。JSONtoClass(responseService mResponseValue.class);然后,类型参数T将被mResponseValue替换,但是您将返回值给mResponseValue ,结果是未检查的cast。

The problematic assignment can be split into two parts:

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

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

So, an easy solution could have been using mResponseValue<mUserStatus>.class as the second parameter of JSONtoClass call, but there is no such thing as mResponseValue<mUserStatus>.class during runtime since type arguments are erased.

因此,一个简单的解决方案可能是使用mResponseValue 。类作为JSONtoClass调用的第二个参数,但是没有mResponseValue 。在运行时类,因为类型参数被删除。

To circumvent this problem, GSON provides methods which accepts java.lang.reflect.Type which preserves generic type information as well. Using them, the warning could be eliminated as follows:

为了解决这个问题,GSON提供了接受java.lang.反射的方法。类型,它还保留泛型类型信息。使用它们,可以消除以下警告:

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

then call like this:

然后调用如下:

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

This solution prevents compiler warnings and actually fixes deserialization/serialization problems which can be caused by lost type information, see Serializing and Deserializing Generic Types in Gson User Guide for more.

此解决方案可防止编译器警告,并实际修复了可能由丢失类型信息引起的反序列化/序列化问题,参见Gson用户指南中对泛型类型的序列化和反序列化。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/08/21/bf4350fd79888e84e6e3475fe397cecd.html



 
  © 2014-2022 ITdaan.com 联系我们: