2015-06-21 108 views
2

我想创建自定义Future对象。自定义未来对象

下面的代码工作正常

ThreadPoolExecutor mExecutor; 
Future<?> f = mExecutor.submit(new DownloadRunnable(task, itemId)); 

我想利用提交的返回值,并将其分配给MyFuture对象,用另外的电话。 我做了以下更改,并获得一个演员异常......任何建议?

ThreadPoolExecutor mExecutor; 
// cast exception 
MyFuture<?> f = (MyFuture<?>) mExecutor.submit(new DownloadRunnable(task, itemId)); 
f.setVer(true); 


public class MyFuture<?> implements Future<?> { 
    Boolean myVar; 

    public void setVar(Boolean v) { 
     ... 
    } 
} 
+0

你为什么要定制'Future'? –

+0

执行者返回它自己的Future类型。你为什么认为你可以把它交给你自己的班级? – RealSkeptic

+0

问题来自提交哪个只返回一个'future ' – Dien

回答

2

你可以通过做一个构造函数Future<?>

public class MyFuture<?> extends Future<?> 
{ 
     Boolean myVar; 
     Future<?> fut; 
     MyFuture<?>(Future<?> fut) 
     { 
      this.fut = fut; 
     } 

     public void setVar(Boolean v) 
     { 
      ... 
     } 
} 

所以下面一行

MyFuture<?> f = (MyFuture<?>) mExecutor.submit(new DownloadRunnable(task, itemId)); 

成为

MyFuture<?> f = new MyFuture<?>(mExecutor.submit(new DownloadRunnable(task, itemId))); 
0

Future是一个接口,你应该写它想:

public class MuFuture<T> implements Future<T> { 

} 

然后,我希望代码将工作:

MyFuture<?> f = (MyFuture<?>) mExecutor.submit(new DownloadRunnable(task, itemId)); 
f.setVer(true); 
+0

我写错了,其实现。我不想实现Future接口,我想要通过ThreadPoolExecutor实现并扩展它。 – aviran