Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use generic T inside a method in java?

Tags:

We can do this in C#:

private T getData<T>(Context context, String url, PostModel postModel) throws ApiException, IOException, ConnectionException {
    Response response = new CallApi<T>(Connection.getApiUrl(context))
            .Post(url, postModel);    
    if (response.code() != 200) throw new ApiException(context,response);

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();
    T obj = gson.fromJson(response.body().charStream(),
            new TypeToken<T>() {
            }.getType());
    return obj;
}

To call:

EmployeeModel model =  getData<EmployeeModel>(context, url, null);

As you can see we declare T as in method signature and inside the method, it replaced with EmployeeModel in CallApi<T> and new TypeToken<T> and it will return EmployeeModel object as the result.

In Java(Android) when I want to use this generic, I have:

private <T> T getData(Context context, String url, PostModel postModel){...}

But it returns me a LinkedTreeMap object and not an EmployeeModel! When I move < T > from method signature to the class itself result is same too.

I search the web and StackOverflow for finding this type of using but articles are just about how to cast T to a model or how to pass it as a parameter.

Please consider that I don't pass T into a method as a parameter and I don't need to cast T to anything. T is used as the type on other generic methods type!

So how can I implement this method in Java?

like image 244
Siamak Ferdos Avatar asked Apr 11 '18 06:04

Siamak Ferdos


People also ask

How do you use T generic in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.

Can method be generic in Java?

Just like type declarations, method declarations can be generic—that is, parameterized by one or more type parameters. We can call this method with any kind of collection whose element type is a supertype of the element type of the array.

Why do we use T in generics?

Yes, the angle-brackets with one (or more) types is the syntax for generics. The T (to confirm, can be any identifier) serves as the placeholder for(in effect, is replaced by) the supplied type.


1 Answers

new TypeToken<T>() {} wouldn't work like you want it to, because of type erasure.

You would have to pass in a TypeToken<T> as a parameter:

EmployeeModel model = getData(
    context, url, null, new TypeToken<EmployeeModel>() {});

changing the method signature to add the extra parameter; then:

T obj = gson.fromJson(response.body().charStream(), typeToken);
like image 145
Andy Turner Avatar answered Sep 28 '22 05:09

Andy Turner