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.
Rohit BajajAsked:
Who is Participating?
 
ste5anSenior DeveloperCommented:
This does not look like a case for a generic. Just normal inheritance. But: even then I don't understand you approach here. A kind of factory method?

As a generic, it must be constrained, thus your different fetch result classes must inherit from the same base class/interface providing your 3 parameter constructor.

E.g. something like this (air-code):

class FetchResult {   
  FetchResult(FetchBuddyMessagesResponse fetchBuddyChats, FetchGroupMessagesResponse fetchGroupChats, ChatsFetchError fetchChatError) { }   
}

class LatestFetchResult extends FetchResult { }

class WhatEver<T extends FetchResult> {
  public static T parseFetchResponse(@Nullable String responseBody,@NotNull GsonBuilder jsonBuilder)
  {
	return new T(fetchBuddyChats, fetchGroupChats, fetchChatError);
  }
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.