此处预期接口(主要活动)

时间:2017-12-11 13:56:03

标签: java android generics interface retrofit

我正在使用改造,我需要为AuthResponse做CommonCallback,以便在我的应用程序中反复使用它。

CommonCallBack.java:

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public abstract class CommonCallBack<RES> implements Callback<RES> {

    @Override
    public void onResponse(Call<RES> call, Response<RES> response) {
        onResSucceeded(call, response);
    }

    protected abstract void onResSucceeded(Call<RES> call, Response<RES> response);

    @Override
    public void onFailure(Call<RES> call, Throwable t) {
        onResFailure(call, t);
    }

    protected abstract void onResFailure(Call<RES> call, Throwable t);


}

MainActivity.java:

public class MainActivity extends AppCompatActivity implements CommonCallBack<AuthResponse> {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ..........
        call.enqueue(this);

    }

    @Override
    protected void onResSucceeded(Call<AuthResponse> call, Response<AuthResponse> response) {

    }

    @Override
    protected void onResFailure(Call<AuthResponse> call, Throwable t) {

    }
  

实现CommonCallBack时出错:此处需要接口

1 个答案:

答案 0 :(得分:0)

使用java 8,您可以使CommonCallBack - 类成为一个接口,并使用default方法进行委托调用:

public interface CommonCallBack<RES> implements Callback<RES> {

    @Override
    default void onResponse(Call<RES> call, Response<RES> response) {
        onResSucceeded(call, response);
    }

    void onResSucceeded(Call<RES> call, Response<RES> response);

    @Override
    default void onFailure(Call<RES> call, Throwable t) {
        onResFailure(call, t);
    }

    void onResFailure(Call<RES> call, Throwable t);
}

这样,您的MainActivity - 类可以实施CommonCallBack