2012-11-09 35 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

非常感謝! –