我是 Java 的新手,我需要用 Java6 编写一个泛型方法。我的目的可以用以下 C# 代码表示。谁能告诉我如何用 Java 编写它?
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 中的编译时特性,所以没有直接的等价物。 typeof(T) 根本不存在。 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);
}
通过这种方式,您需要调用者以一种使类型在运行时可用的方式编写代码。
