Question

Scenario: I need to handle a request and response scenario where the inner objects of request/response depends on the request code. so I did a method like below.

public static <T, U> Response getResponse(String requestCode, Request req) {
        Response response = new Response();

        T requestObject = (T) req.getInnerObject();

        RequestHandler<T, U> requestHandler = new RequestHandler<T, U>(
                requestCode, requestObject);

        U responseObject = requestHandler.getResponse();

        response.setInnerObject(responseObject);

        return response;
}

The question is, How do I specify the T and U when calling this method? I'm surprised that I can do

Response response = getResponse(requestCode, req);

Where have I got it wrong?

Thanks.

Was it helpful?

Solution

To specifiy T and U, you can call your method like this :

YourClass.<MyTClass, MyUClass>getResponse(requestCode, req);

Calling Response response = getResponse(requestCode, req); is as valid as calling new ArrayList() instead of new ArrayList<String>().

OTHER TIPS

You are using a generic method. Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

To reference the generic method within your code, you must perform a generic type invocation, which replaces T and U with some concrete value, such as Integer:

SomeClass.<Integer, String>getResponse(requestCode, req);

Sometimes, the explicitly provided types can be left out and the compiler will infer the type that is needed. This feature, known as type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets. Read about type inference to know more about this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top