简体   繁体   English

Java:泛型捕获错误

[英]Java: Generics capture error

I'm trying to make the following code work with no success 我正在尝试使以下代码无法成功运行

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 class looks like this: 捕获类如下所示:

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

With this code I'm having the following compilation error: 使用此代码,我遇到以下编译错误:

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

If I replace 如果我更换

backgroundTask.execute(arg);

with

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

I'm not having any compilation error anymore, but I have a ClassCastException at Runtime. 我不再有任何编译错误,但是在运行时出现ClassCastException。 Is there a way to pass an instance of the BackgroundTask + the argument to my function ? 有没有办法将BackgroundTask的实例+参数传递给我的函数?

Edit: I forget the code from where I call the confirmBackgroundAction() method... 编辑:我忘记了从我调用confirmBackgroundAction()方法的代码...

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

Where SpecificBackgroundTask looks like 哪里的SpecificBackgroundTask看起来像

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

At compile time, the T in BackgroundTask<T> is unknown and can at most (theoretically) store 1 type T of multiple possible types with which you can call confirmBackgroundAction() . 在编译时,该TBackgroundTask<T>是未知的,并且可以为至多(理论上)存储1型的多个可能类型的T,带,其可以调用confirmBackgroundAction()

The compiler has no way to solve this consistently. 编译器无法始终如一地解决这个问题。 Changing T into an interface you define would fix the ambiguity. T更改为您定义的interface将解决歧义。

Try this 尝试这个

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);
  }
}

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

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