Miles Chen
Miles Chen

Reputation: 793

How to write generic method in Java

I'm new to Java and I need to write a generic method in Java6. My purpose can be represented by the following C# code. Could someone tell me how to write it in 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);
    }

    ...
}

Upvotes: 1

Views: 226

Answers (2)

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

Several issues-
A. Generics are more "weak" in Java than in C#.
no "typeof, so you must pass Class parameters representing typeof.
B. Your signature must also include K and P at the generic definition.
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);
}

Upvotes: 1

Affe
Affe

Reputation: 47984

Because Generics are a compile-time only feature in Java, there is no direct equivalent. typeof(T) simply does not exist. One option for a java port is for the method to look more like this:

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.

Upvotes: 3

Related Questions