Java:可以匿名内部类扩展吗? [英] Java:can annonymous inner classes extend?
本文介绍了Java:可以匿名内部类扩展吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个扩展另一个类的匿名内部类。
我想做的事情实际上是这样的:
for(final e:list){
Callable< V> l = new MyCallable(ev)extends Callable< V>(){
private e; //由构造函数更新
@Override
public V call()throws Exception {
if (e!= null)return e;
else {
// do something heavy
}
}
};
FutureTask< V> f = new FutureTask V(1);
futureLoadingtask.run();
}
}
解决方案
你不能给你的匿名类名字,这就是为什么它被称为匿名。我看到的唯一选项是从 Callable
final
$ b
//你的外循环
for(;;){
//创建一个最终的声明`
final E e = ...
Callable< E> c = new Callable< E> {
//你可以有类变量
private String x;
//这是在匿名类中实现构造函数逻辑的唯一方法:
{
//在构造函数中使用e做一些事情
x = e.toString );
}
E call(){
if(e!= null)return e;
else {
// long task here ....
}
}
}
}
另一种选择是将本地类(不是匿名类)范围限定为:
public void myMethod(){
// ...
class MyCallable< E>实现可调用< E> {
public MyCallable(E e){
//构造函数
}
E call(){
//实现...
}
}
//现在你可以使用local类(不是匿名)
MyCallable< String> my = new MyCallable< String>(abc);
// ...
}
创建常规
MyCallable
类...I want to create an annonymous inner class that extends another class.
What I want to do is actually something like the following:
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(); } }
Is this possible?
解决方案You cannot give a name to your anonymous class, that's why it's called "anonymous". The only option I see is to reference a
final
variable from the outer scope of yourCallable
// 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.... } } } }
Another option is to scope a local class (not anonymous class) like this:
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"); // ... }
If you need more than that, create a regular
MyCallable
class...这篇关于Java:可以匿名内部类扩展吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文