我们可以在C#中做到这一点:
private T getData(Context context, String url, PostModel postModel) throws ApiException, IOException, ConnectionException {
Response response = new CallApi(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() {
}.getType());
return obj;
}
致电:
EmployeeModel model = getData(context, url, null);
正如您所看到的,我们在方法签名中声明了T,并且在方法内部,它被CallApi< T>中的EmployeeModel替换.和新的TypeToken< T>它将返回EmployeeModel对象作为结果.
在Java(Android)中,当我想使用这个泛型时,我有:
private T getData(Context context, String url, PostModel postModel){...}
但它返回一个LinkedTreeMap对象而不是EmployeeModel!当我移动< T>从方法签名到类本身的结果也一样. 我搜索网络和StackOverflow以找到这种类型的使用,但文章只是关于如何将T转换为模型或如何将其作为参数传递.
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!
那么如何在Java中实现这个方法呢?