在抽象基类

时间:2015-07-02 16:56:11

标签: java android generics constructor

我创建了一个带有三个构造函数的抽象基类BaseModelDao。当我创建一个扩展SubscriberScoreDao的类BaseModelDao时,我必须重新定义子类中的所有三个构造函数,以避免编译时错误。有没有办法利用我在BaseModelDao中定义的构造函数,而不必在每个子类中重新实现相同的逻辑?

BaseModelDao

public abstract class BaseModelDao<T extends Model> {

    private static final String TAG = BaseModelDao.class.getSimpleName();

    private List<T> mModelList;

    protected BaseModelDao() {
        mModelList = new ArrayList<>();
    }

    protected BaseModelDao(Response<T>[] responseArray) {
        mModelList = fromResponseArray(responseArray);
    }

    protected BaseModelDao(Response<T> response) {
        mModelList = fromResponse(response);
    }

    public List<T> getModelList() {
        return mModelList;
    }

    public abstract Class<T> getModelClass();

    private List<T> fromResponse(Response<T> response) {
        List<T> responseList = response.getResultData();
        return responseList;
    }

    public List<T> fromResponseArray(Response<T>[] responseArray) {
        return fromResponse(getResponseObjectFromArray(responseArray));
    }

    // more helper methods...

}

SubscriberScoreDao

public class SubscriberScoreDao extends BaseModelDao<SubscriberScore> {

    public static final String TAG = SubscriberScoreDao.class.getSimpleName();

    public SubscriberScoreDao(){
        super();
    }

    public SubscriberScoreDao(Response<SubscriberScore>[] responseArray) {
        super(responseArray);
    }

    public SubscriberScoreDao(Response<SubscriberScore> responseArray) {
        super(responseArray);
    }

    @Override
    public Class<SubscriberScore> getModelClass() {
        return SubscriberScore.class;
    }
}

上面显示的构造函数是我想要消除的构造函数。当我想在代码中使用SubscriberScoreDao时,它看起来像这样。

    LendingRestClient.getInstance().getSubscriberScoring(new Callback<Response<SubscriberScore>[]>() {
        @Override
        public void success(Response<SubscriberScore>[] responseArray, retrofit.client.Response response) {
            mSubscriberScoreDao = new SubscriberScoreDao(responseArray);
        }

        @Override
        public void failure(RetrofitError error) {

        }
    });

如果在super()中未定义调用SubscriberScoreDao的三个构造函数,则代码会在此行引发编译时错误:

  

mSubscriberScoreDao = new SubscriberScoreDao(responseArray);

错误: Error Message

有没有办法不在每个子类中定义构造函数并避免此错误?

1 个答案:

答案 0 :(得分:1)

您可以使用vararg声明构造函数(在基类中):

class Super<T> {
    private List<T> responses;

    public Super(Response<T>...responses) {
        this.responses = Arrays.asList(responses);
    }
}

您的子类只需要声明1个构造函数,它将处理您拥有的所有3个构造函数的功能。

class Sub extends Super<SubscriberScore> {
    public Sub(Response<SubscriberScore>...responses) {
        super(responses);
    }
}

您现在可以将Sub实例化为:

new Sub();
new Sub(new Response<SubscriberScore>());
new Sub(new Response<SubscriberScore>[] {

});