我想创建一个扩展另一个类的匿名内部类。
实际上,我要执行的操作如下:
for(final e:list){ Callable<V> l = new MyCallable(e.v) extends Callable<V>(){ private e;//updated by constructor @Override public V call() throws Exception { if(e != null) return e; else{ //do something heavy } } }; FutureTask<V> f = new FutureTask<V>(l); futureLoadingtask.run(); } }
这可能吗?
您不能给匿名类命名,这就是为什么它被称为“匿名”的原因。我看到的唯一选择是final从您的外部范围引用变量Callable
final
Callable
// Your outer loop for (;;) { // Create some final declaration of `e` final E e = ... Callable<E> c = new Callable<E> { // You can have class variables private String x; // This is the only way to implement constructor logic in anonymous classes: { // do something with e in the constructor x = e.toString(); } E call(){ if(e != null) return e; else { // long task here.... } } } }
另一个选择是像这样定义一个本地类(不是匿名类):
public void myMethod() { // ... class MyCallable<E> implements Callable<E> { public MyCallable(E e) { // Constructor } E call() { // Implementation... } } // Now you can use that "local" class (not anonymous) MyCallable<String> my = new MyCallable<String>("abc"); // ... }
如果您还需要更多,请创建一个常规MyCallable类…
MyCallable