7

我定义了以下类:

class Operation<S>
class GetReservationOperation extends Operation<Reservation>

现在我想要一个这样的课程:

OperationExecutor<T extends Operation<S>> extends AsyncTask<T,Void,S>{
    @Override
    protected S doInBackground(T... params) {
       return null;
    }
}

但这不会编译:

OperationExecutor<GetReservationOperation> executor = new ....

为什么Java不允许这样做?

一段时间后,我想出了以下解决方案:

OperationExecutor<T extends Operation<S>,S> extends AsyncTask<T,Void,S>{
    @Override
    protected S doInBackground(T... params) {
       return null;
    }
}

但这迫使我写下以下内容:

OperationExecutor<GetReservationOperation,Reservation> executor = new .... 

这看起来很奇怪。有什么办法让它看起来更好看吗?

编辑 这工作

OperationExecutor<S> extends AsyncTask<Operation<S>,Void,S>{
    @Override
    protected S doInBackground(Operation<S>... params) {
       return null;
    }
}

OperationExecutor<Reservation> executor = new ....
executor.execute(getReservationOperation);
4

1 回答 1

3

现在我想上这样的课

OperationExecutor<T extends Operation<S>> extends AsyncTask<T,Void,S>{
    @Override
    protected S doInBackground(T... params) {
       return null;
    }
}

这不起作用的原因是因为S没有在任何地方声明T,只在's bound中作为类型参数引用。需要声明 JavaS以便其他对它的引用才有意义,例如protected S doInBackgroundAsyncTask<T,Void,S>.

您可能会考虑的一件事是是否OperationExecutor需要对特定类型的Operation<S>. 你可以这样做,例如:

OperationExecutor<S> extends AsyncTask<Operation<S>, Void, S> {
    @Override
    protected S doInBackground(Operation<S>... params) {
       return null;
    }
}
于 2013-04-25T21:26:00.270 回答