C# 如何用Java编写泛型方法
我是Java新手,需要用Java6编写一个通用方法。我的目的可以用下面的C代码表示。有人能告诉我如何用Java编写吗C# 如何用Java编写泛型方法,c#,java,generics,C#,Java,Generics,我是Java新手,需要用Java6编写一个通用方法。我的目的可以用下面的C代码表示。有人能告诉我如何用Java编写吗 class Program { static void Main(string[] args) { DataService svc = new DataService(); IList<Deposit> list = svc.GetList<Deposit, DepositParam, DepositParamLi
class Program
{
static void Main(string[] args)
{
DataService svc = new DataService();
IList<Deposit> list = svc.GetList<Deposit, DepositParam, DepositParamList>();
}
}
class Deposit { ... }
class DepositParam { ... }
class DepositParamList { ... }
class DataService
{
public IList<T> GetList<T, K, P>()
{
// build an xml string according to the given types, methods and properties
string request = BuildRequestXml(typeof(T), typeof(K), typeof(P));
// invoke the remote service and get the xml result
string response = Invoke(request);
// deserialize the xml to the object
return Deserialize<T>(response);
}
...
}
因为泛型在Java中是一种只在编译时使用的特性,所以没有直接的等价物。typeofT根本不存在。java端口的一个选项是让方法看起来更像这样:
public <T, K, P> List<T> GetList(Class<T> arg1, Class<K> arg2, Class<P> arg3)
{
// build an xml string according to the given types, methods and properties
string request = BuildRequestXml(arg1, arg2, arg3);
// invoke the remote service and get the xml result
string response = Invoke(request);
// deserialize the xml to the object
return Deserialize<T>(response);
}
通过这种方式,您需要调用方以使类型在运行时可用的方式编写代码。因为泛型在Java中是仅编译时的功能,所以没有直接的等价物。typeofT根本不存在。java端口的一个选项是让方法看起来更像这样:
public <T, K, P> List<T> GetList(Class<T> arg1, Class<K> arg2, Class<P> arg3)
{
// build an xml string according to the given types, methods and properties
string request = BuildRequestXml(arg1, arg2, arg3);
// invoke the remote service and get the xml result
string response = Invoke(request);
// deserialize the xml to the object
return Deserialize<T>(response);
}
通过这种方式,您需要调用方以使类型在运行时可用的方式编写代码。有几个问题-
泛型在Java中比在C中更弱。
没有typeof,因此必须传递表示typeof的类参数。
B.您的签名还必须包括通用定义中的K和P。
因此,代码如下所示:
若干问题-
泛型在Java中比在C中更弱。
没有typeof,因此必须传递表示typeof的类参数。
B.您的签名还必须包括通用定义中的K和P。
因此,代码如下所示:
不需要使用反序列化,我只是用JDK 6Thanks检查了一下,你们两个,Affe和zaske。答案在我看来有点奇怪。但这真的很有帮助!不需要使用反序列化,我只是用JDK 6Thanks检查了一下,你们两个,Affe和zaske。答案在我看来有点奇怪。但这真的很有帮助!