匿名类的输出?

rip*_*234 0 java closures exception anonymous-types

如何从Java匿名类中获取输出?在.Net中我会使用闭包.

executor = Executors.newSingleThreadExecutor();
final Runnable runnable = new Runnable() {
  public Exception exception;

  @Override
  public void run() {
    try {
      doSomething();
    }
    catch (Exception exception) {
      // I'd like to report this exception, but how?
      // the exception member is not readable from outside the class (without reflection...)
      this.exception = exception;
    }
  }
};

executor.submit(runnable);

// Here I'd like to check if there was an exception
Run Code Online (Sandbox Code Playgroud)

and*_*dri 7

Executor接口提供了没有办法做到这一点.但是,当您打电话时,newSingleThreadExecutor()您将获得ExecutorService包含该功能的功能.

调用ExecutorService.submit()返回一个实例Future<?>,您可以使用它来获取计算的结果值.

如果执行导致异常,则调用get将导致ExecutionException抛出异常.