Rohit Bajaj
asked on
Using Generics in java
Hi,
I have the following code :
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(@Nullab le String responseBody,@NotNull GsonBuilder jsonBuilder)
{
.
.
.
.
return return new T(fetchBuddyChats, fetchGroupChats, fetchChatError);
But this is giving error.
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);
}
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(@Nullab
{
.
.
.
.
return return new T(fetchBuddyChats, fetchGroupChats, fetchChatError);
But this is giving error.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.