類型安全:類型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 联系我们: