繁体   English   中英

如何在Java中编写泛型方法

[英]How to write generic method in Java

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

    ...
}

因为Generics是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);
}

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

几个问题 -
A.泛型在Java中比在C#中更“弱”。
没有“typeof,所以你必须传递表示typeof的Class参数。
B.您的签名还必须包括通用定义中的K和P.
所以代码看起来像:

public <T,K,P> IList<T> GetList(Class<T> clazzT, Class<K> claszzK,lass<P> clazzP) {
    String request = buildRequestXml(clazzT, clazzK, clazzP);
    String response = invoke(request);
    return Deserialize(repsonse);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM