【发布时间】:2012-12-30 20:59:43
【问题描述】:
当然,我对所有这些 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
}
我想要做的是获取 Type "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>?
此外,当我试图通过“类型”参数显式传递类型时,它只会导致我这样的编译时间错误。
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
}
那么,如果这些尝试都无效,我该如何设置反序列化的类型?
【问题讨论】:
-
请遵循公认的 Java 方法名称约定。
GetInstanceService应该是getInstanceService。 -
thing是类还是实例?如果是实例,则不能用作参数化表达式中的参数。 -
当然,
GetInstanceService(Type type)中的type不能在new ArrayList<type>()中使用,因为它不是一个类... -
yair: thing 是一个类,因为我调用了 comm 之类的方法。
GetInstanceService("listTestType");