简体   繁体   English

如何在Java中编写泛型方法

[英]How to write generic method in Java

I'm new to Java and I need to write a generic method in Java6. 我是Java的新手,我需要在Java6中编写泛型方法。 My purpose can be represented by the following C# code. 我的目的可以用以下C#代码表示。 Could someone tell me how to write it in Java? 有人能告诉我如何用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);
    }

    ...
}

Because Generics are a compile-time only feature in Java, there is no direct equivalent. 因为Generics是Java中仅编译时的特性,所以没有直接的等价物。 typeof(T) simply does not exist. typeof(T)根本就不存在。 One option for a java port is for the method to look more like this: 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);
}

This way you require the caller to write the code in a way that makes the types available at runtime. 这样,您需要调用者以在运行时使类型可用的方式编写代码。

Several issues- 几个问题 -
A. Generics are more "weak" in Java than in C#. A.泛型在Java中比在C#中更“弱”。
no "typeof, so you must pass Class parameters representing typeof. 没有“typeof,所以你必须传递表示typeof的Class参数。
B. Your signature must also include K and P at the generic definition. B.您的签名还必须包括通用定义中的K和P.
So the code will look like: 所以代码看起来像:

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