匿名类的输出?

时间:2009-06-30 15:54:42

标签: java exception closures 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

5 个答案:

答案 0 :(得分:7)

Executor界面无法执行此操作。但是,当您致电newSingleThreadExecutor()时,您将获得一个ExecutorService,其中包含相应的功能。

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

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

答案 1 :(得分:2)

要从执行程序上运行的任务获取异常,您要使用Callable而不是Runnable。

Callable的call()方法可以抛出已检查的异常。当你在Future实例上调用get()时,如果你的call()方法抛出了一个已检查的异常,它将抛出一个ExecutionException。然后,您可以通过在ExecutionException上调用getCause()来访问基础检查的异常。

答案 2 :(得分:0)

Hackish ....但是,你可以有一个静态变量/方法,Runnable调用它来报告异常

public class Driver {
static Exception exec;
static final Runnable runnable = new Runnable() {
    public Exception exception;

    public void run() {
      try {
          throw new Exception("asdf");
      }
      catch (Exception exception) {
          exec = exception;
      }
    }
  };

public static void main(String[] args) throws Exception{
    ExecutorService e = Executors.newSingleThreadExecutor();
    e.submit(runnable);
    e.shutdown();
    while(e.isShutdown()==false){
        Thread.sleep(2000);
    }
    System.out.println(exec);

}

答案 3 :(得分:0)

您可以在RuntimeException中包装抛出的异常并将executor.submit()调用放在try / catch块中:

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

 @Override
  public void run() {
    try {
     doSomething();
    } catch (Exception exception) {
       throw new RuntimeException(exception);
    }
  }
};

try{ 
 executor.submit(runnable);
} catch (Throwable t) {
  Throwable cause = t.getCause();
  //do what you want with the cause
}

答案 4 :(得分:-2)

如果将异常声明为final,则匿名类将能够存储该值,并且可以在run()完成时检查变量。

编辑添加:抱歉,我的意思是让它成为一个例外的最终数组。 Idea会自动为我执行此操作,因此我经常忘记额外的重定向。

final Exception[] except;