gpt4 book ai didi

c# - 如何在 Java 中编写泛型方法

转载 作者:太空宇宙 更新时间:2023-11-03 21:53:41 26 4
gpt4 key购买 nike

我是 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);
}

通过这种方式,您需要调用者以一种使类型在运行时可用的方式编写代码。

关于c# - 如何在 Java 中编写泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13302767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com