Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Using Generics in java

Hi,
I have the following code :
public static LatestFetchResponse parseFetchResponse(@Nullable String responseBody,@NotNull GsonBuilder jsonBuilder)
    {
        FetchBuddyMessagesResponse fetchBuddyChats = new FetchBuddyMessagesResponse();
        FetchGroupMessagesResponse fetchGroupChats = new FetchGroupMessagesResponse();
        ChatsFetchError fetchChatError = new ChatsFetchError();

        Gson gson = jsonBuilder.create();

        JsonParser jsonParser = new JsonParser();
        JsonElement object = jsonParser.parse(responseBody).getAsJsonObject();

        if (Utils.isFetchError(object))
        {
            fetchChatError = gson.fromJson(object, ChatsFetchError.class);
        }
        else
        {
            if (Utils.isBuddyChat(object))
            {
                fetchBuddyChats = gson.fromJson(object, FetchBuddyMessagesResponse.class);
            }
            else
            {
                fetchGroupChats = gson.fromJson(object, FetchGroupMessagesResponse.class);
            }
        }


        return new LatestFetchResponse(fetchBuddyChats, fetchGroupChats, fetchChatError);
    }

Open in new window


The above code is repeated in many classes except the class name LatestFetchResponse gets changed.

How do i take it out and make it a generic function.

I tried something like :
    public static <T> T parseFetchResponse(@Nullable String responseBody,@NotNull GsonBuilder jsonBuilder)
{
.
.
.
.
return         return new T(fetchBuddyChats, fetchGroupChats, fetchChatError);

But this is giving error.
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial