泛型类型args哪个特定扩展类? [英] Generic type args which specificy the extending class?

查看:135
本文介绍了泛型类型args哪个特定扩展类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个实现一个接口的类,它将特定的子类指定为一个参数。

  public abstract Task实现TaskStatus< Task> {
TaskStatus< T>侦听器;

protected complete(){
// ugly,unsafe cast
callback.complete((T)this);
}
}

public interface TaskStatus< T> {
public void complete(T task);
}

但是,而不是仅仅是任务,或者,我想保证type-arg使用的是特定类的扩展这一个。



所以我想出的最好的是:

  public abstract Task< T extends Task>实现TaskStatus< T> {
}

您可以写下来:

  public class MyTask extends Task< MyTask> {
}

但这也是有效的:

  public class MyTask extends Task< SomeOtherTask> {
}

并且回调的调用将会与ClassCastException一起爆炸。那么这种做法是错误的,还是有错误的方法呢?

解决方案

您不清楚您在任务之内所做的尝试。但是,如果您定义泛型类 Task< T> 如下:

 类任务< T扩展任务< T>> {...} 

以下两个可能:

  class MyTask extends Task< MyTask> {...} 
class YourTask extends Task< MyTask> {...}

但以下是禁止的:

  class MyTask extends Task< String> {...} 

上述任务定义使用F边界多态,一个相当高级的功能。您可以查看研究论文面向对象的F边界多态编程了解更多信息。


I want to have a class which implements an interface, which specifies the specific subclass as a parameter.

public abstract Task implements TaskStatus<Task> {
  TaskStatus<T> listener;

  protected complete() {
      // ugly, unsafe cast
      callback.complete((T) this);
  }
}

public interface TaskStatus<T> {
   public void complete(T task);
}

But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one.

So the best I've come up with is:

public abstract Task<T extends Task> implements TaskStatus<T> {
}

You'd extend that by writing:

public class MyTask extends Task<MyTask> {
}

But this would also be valid:

public class MyTask extends Task<SomeOtherTask> {
}

And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I've somehow missed?

解决方案

It is not clear what you are trying to do inside of Task. However, if you define the generic class Task<T> as follows:

class Task<T extends Task<T>> { ... }

The following two are possible:

class MyTask extends Task<MyTask> { ... }
class YourTask extends Task<MyTask> { ... }

But the following is prohibited:

class MyTask extends Task<String> { ... }

The above definition of Task uses F-bounded polymorphism, a rather advanced feature. You can check the research paper "F-bounded polymorphism for object-oriented programming" for more information.

这篇关于泛型类型args哪个特定扩展类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆