2012-11-09 36 views
1

我是Java新手,需要在Java6中编写通用方法。我的目的可以用下面的C#代码来表示。有人能告诉我如何在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); 
    } 

    ... 
} 

回答

3

因为泛型只是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); 
} 

你需要调用者编写代码的方式,使得在运行时可用的类型本办法。

+0

无需在Deserialize中使用(我刚刚用JDK 6检查过) –

+0

谢谢你们,Affe和zaske。答案看起来有点奇怪,但它确实有帮助! –

1

几个问题 -
答:泛型在Java中比在C#中更“弱”。
没有“的typeof,所以你必须通过类参数代表的typeof
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); 
} 
+0

非常感谢! –