在 Android 中将嵌套类<MyInterface<T>> 作为参数传递
我正在尝试创建一个包装器来抽象我的服务实现。到目前为止,我已经让编译器成功编译:Retrofit
package com.example.spark.testapp.services;
import com.example.spark.testapp.services.apis.Get;
import com.example.spark.testapp.services.apis.Post;
import com.example.spark.testapp.services.utils.*;
import com.example.spark.testapp.services.utils.Error;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class ServiceLayer {
public <T> void performGet(String url, final Class<Get<T>> clazz, com.example.spark.testapp.services.utils.Callback<T> callback) {
Retrofit retrofit = new Retrofit.Builder().baseUrl("").build();
Get<T> service = retrofit.create(clazz);
//Pass authentication token here
Call<T> t = service.get(url, "");
executeCallback(callback,t);
}
public <T> void performPost(String url, final Class<Post<T>> clazz,com.example.spark.testapp.services.utils.Callback<T> callback) {
Retrofit retrofit = new Retrofit.Builder().baseUrl("").build();
Post<T> service = retrofit.create(clazz);
//Pass authentication token here
Call<T> t = service.post(url, "");
executeCallback(callback,t);
}
public <T> void executeCallback( final com.example.spark.testapp.services.utils.Callback<T> callback , Call<T> call) {
call.enqueue(new Callback<T>() {
@Override
public void onResponse(Call<T> call, Response<T> response) {
callback.onSuccess(response.body());
}
@Override
public void onFailure(Call<T> call, Throwable t) {
///Find out what exactly went wrong. Populate Error. and then...
com.example.spark.testapp.services.utils.Error e = new Error();
callback.onFailure(e);
}
});
}
}
在编译时,问题出在调用方法的点上:
private void getString() {
ServiceLayer s = new ServiceLayer();
s.performGet("",Get<String>.class,this); //Cannot select from parameterised type
}
我用谷歌搜索了一下,发现由于类型擦除,这是不可能的。好。
但我的问题是,编译器不应该在这里引发错误吗?在这一行?:
public <T> void performGet(String url, final Class<Get<T>> clazz, com.example.spark.testapp.services.utils.Callback<T> callback)
我的服务层是如何编译的?
编辑
这个问题似乎被误解了。我不是在寻找一种方法来让这个设计工作。我理解其中的缺陷,我们已经找到了更好的方法来分层我们的服务。问题在于语言本身的有趣/怪异行为。