I am trying to create a wrapper over Retrofit
to abstract my service implementation. I have gotten the compiler to compile successfully so far:
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);
}
});
}
}
While this compiles, the problem is at the point of calling the method:
private void getString() {
ServiceLayer s = new ServiceLayer();
s.performGet("",Get<String>.class,this); //Cannot select from parameterised type
}
I Googled around this a bit and found out that this is not possible due to type erasure. Fine.
But my question is, shouldn't the compiler raise an error here? At this line? :
public <T> void performGet(String url, final Class<Get<T>> clazz, com.example.spark.testapp.services.utils.Callback<T> callback)
How did my service layer get compiled?
EDIT
The question seems to be misunderstood. I am not looking for a way to get this design to work. I understand the flaw in it and we have found a better way to layer our services. The question is about the interesting/weird behaviour of the language itself.