1

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

    ...
}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No need to use <T> at Deserialize (I just checked it with JDK 6)
Thanks both of you, Affe and zaske. The answer looks a little bit weird to me. But it's really helpful!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.