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 castT
to anything. T is used as the type on other generic methods type!
So how can I implement this method 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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With