当然,我对所有这些 Java 东西都很陌生,所以我有一个问题,我正在尝试反序列化在 WCF 服务上获得的响应,一切正常,但是,我正在尝试创建一个通用函数来做到这一点。
基本上我所做的是
public List<msg> GetService(String method){
List<msg> response = new ArrayList<msg>();
Type msgType = new TypeToken<List<msg>>(){}.getType();
//Obtaining result
response = uJSON.fromJson(serviceResponse, msgType);
//uJSON is an instance of Gson library, for deserializing it just needs
//the service response and a Class<T> or Type to reflect the obtained message
}
我想做的是获取类型“msg”泛型,这意味着......
public <thing> void GetInstanceService(String method){
List<thing> response = new ArrayList<thing>();
Type rType2 = new TypeToken<List<thing>>(){}.getType(); //Got java.util.List<thing>
//And when I'm trying to deserialize I just obtain a List of object
//[java.lang.Object@5c7a987e, java.lang.Object@74b1a7a0]
type2 = uJSON.fromJson(new String(entity), rType2);
}
但我是这样打电话的。
comm.<msgType>GetInstanceService("listTestType");
所以,当我调用“GetInstanceService”时,“thing”是“msgType”类型,对于
List<thing>
而且响应也不应该是 List<msgType>
而不是List <Object>
?
此外,当我尝试通过“Type”参数显式传递类型时,它只会导致像这样的编译时错误。
public void GetInstanceService(Type type){
List<type> type2 = new ArrayList<type>(); //Compilation time error
//Or
msgType oType = new msgType();
Class classType = oType.getClass();
List<classType> type3; //Compilation time error
}
那么,如果这些尝试都无效,我该如何设置反序列化的类型?
最佳答案
Guava 类 TypeToken
不支持该使用模式。您正在使用类型变量创建类型标记,但没有足够的信息来重建 List<String>
来自List<T>
。您应该创建 TypeToken
的实例您拥有所有必需的编译时信息。
文档说:
Note that it's critical that the actual type argument is carried by a subclass. The following code is wrong because it only captures the
<T>
type variable of thelistType()
method signature; while<String>
is lost in erasure:class Util { static <T> TypeToken<List<T>> listType() { return new TypeToken<List<T>>() {}; } } TypeToken<List<String>> stringListType = Util.<String>listType();
但是如上所述,您可以实例化 TypeToken
在调用站点,所有类型信息都可用,然后将其作为参数传递。像这样的事情:
public <thing> void GetInstanceService(String method, TypeToken<List<thing>> token){
List<thing> response = new ArrayList<thing>();
Type rType2 = token.getType();
type2 = uJSON.fromJson(new String(entity), rType2);
}
comm.GetInstanceService("listTestType", new TypeToken<List<msgType>>() {});
更新
Paul Bellora 指出您还可以接受参数 TypeToken<thing> token
,并构建 TypeToken<List<thing>>
token
的方法内部:
public <thing> void GetInstanceService(String method, TypeToken<thing> token) {
List<thing> response = new ArrayList<thing>();
Type rType2 = new TypeToken<List<thing>>() {}
.where(new TypeParameter<thing>() {}, token); // where() binds "thing" to token
.getType();
type2 = uJSON.fromJson(new String(entity), rType2);
}
comm.GetInstanceService("listTestType", new TypeToken<msgType>() {});
关于java - Java通过参数获取类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14094600/