简体   繁体   English

Java泛型 - 推断嵌套类型

[英]Java generics - inferring nested type

I have defined following classes: 我定义了以下类:

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

Now I would like to have a class like this: 现在我想要一个这样的课程:

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

But this won't compile: 但这不会编译:

OperationExecutor<GetReservationOperation> executor = new ....

Why doesn't Java allow this? 为什么Java不允许这样做?

After some time I came up with the following solution: 过了一段时间我想出了以下解决方案:

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

But this forces me to write the following: 但这迫使我写下以下内容:

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

Which looks odd. 这看起来很奇怪。 Is there any way to make it look nicer? 有没有办法让它看起来更好?

EDIT This worked 编辑这个工作

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

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

Now I would like to have a class like this 现在我想要一个像这样的课程

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

The reason this doesn't work is because S hasn't been declared anywhere, only referenced as a type argument in T 's bound. 这不起作用的原因是因为S没有在任何地方声明 ,只是作为T绑定中的类型参数引用。 Java needs S to be declared for other references to it to make sense, for example protected S doInBackground and AsyncTask<T,Void,S> . Java需要S被宣布为它的其他引用意义,例如protected S doInBackgroundAsyncTask<T,Void,S>

One thing you might consider is whether OperationExecutor needs to be generic to a specific type of Operation<S> . 您可能会考虑的一件事是OperationExecutor是否需要对特定类型的Operation<S>是通用的。 You could do this instead for example: 你可以这样做,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM