且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

匿名内部类可以扩展吗?

更新时间:2023-02-15 20:13:41

你不能给你的匿名类命名,这就是为什么它被称为匿名。我看到的唯一选择是从 Callable

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 your 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....
      }
    }
  }
}

另一种选择是对本地类(非匿名类)的范围如下:

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");
  // ...
}

如果您需要更多,创建一个普通的 MyCallable 类......

If you need more than that, create a regular MyCallable class...