我试图在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 void performGet(String url, final Class> clazz, com.example.spark.testapp.services.utils.Callback callback) {
Retrofit retrofit = new Retrofit.Builder().baseUrl("").build();
Get service = retrofit.create(clazz);
//Pass authentication token here
Call t = service.get(url, "");
executeCallback(callback,t);
}
public void performPost(String url, final Class> clazz,com.example.spark.testapp.services.utils.Callback callback) {
Retrofit retrofit = new Retrofit.Builder().baseUrl("").build();
Post service = retrofit.create(clazz);
//Pass authentication token here
Call t = service.post(url, "");
executeCallback(callback,t);
}
public void executeCallback( final com.example.spark.testapp.services.utils.Callback callback , Call call) {
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
callback.onSuccess(response.body());
}
@Override
public void onFailure(Call 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.class,this); //Cannot select from parameterised type
}
我在这里聊了一下,发现这是不可能的,因为类型擦除.精细.
但我的问题是,编译器不应该在这里提出错误吗?在这一行? :
public void performGet(String url, final Class> clazz, com.example.spark.testapp.services.utils.Callback callback)
我的服务层如何编译?
编辑
这个问题似乎被误解了.我不是在寻找一种让设计工作的方法.我了解其中的缺陷,我们找到了更好的方式来分层我们的服务.问题是关于语言本身的有趣/奇怪的行为.