Java:泛型捕获错误

时间:2012-03-10 10:42:15

标签: java generics capture

我正在尝试使以下代码无法正常工作

protected BackgroundTask<?> backgroundTask = null;

...

protected <T> void confirmBackgroundAction(final BackgroundTask<T> task, final T arg) {
   backgroundTask = task;
   backgroundTask.attach(AbstractWorkerActivity.this);
   backgroundTask.execute(arg);
}

Capture类看起来像这样:

public abstract class BackgroundTask<T> extends AsyncTask<T, Void, Long> {
...
}

使用此代码我遇到以下编译错误:

The method execute(capture#26-of ?...) in the type AsyncTask<capture#26-of ?,Void,Long> is not applicable for the arguments (T)

如果我更换

backgroundTask.execute(arg);

((BackgroundTask<T>)backgroundTask).execute(arg);

我不再有任何编译错误,但我在运行时遇到了ClassCastException。 有没有办法将BackgroundTask +参数的实例传递给我的函数?

编辑:我忘记了调用confirmBackgroundAction()方法的代码......

confirmBackgroundAction(new SpecificBackgroundTask(), (Void) null);

其中SpecificBackgroundTask看起来像

public class SpecificBackgroundTask extends BackgroundTask<Void> {
...
}

2 个答案:

答案 0 :(得分:1)

在编译时,T中的BackgroundTask<T>是未知的,并且最多(理论上)可以存储多种可能类型的1种类型T,您可以使用这些类型调用confirmBackgroundAction()

编译器无法一致地解决这个问题。将T更改为您定义的interface可以解决歧义问题。

答案 1 :(得分:0)

试试这个

class Klass {


  protected BackgroundTask<?> backgroundTask = null;

...

  protected <T> void confirmBackgroundAction(final BackgroundTask<T> task, Object arg) {
     backgroundTask = task;
     backgroundTask.attach(AbstractWorkerActivity.this);
     backgroundTask.execute( (T) arg);
  }
}