How can I get output from Java anonymous classes? In .Net I would use closures.
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
The
Executorinterface offers no way to do this. However, when you callnewSingleThreadExecutor()you will get anExecutorServicewhich contains functionality for that.Calling
ExecutorService.submit()returns an instance ofFuture<?>, which you can use to get the result value of the computation.If the execution resulted in an exception, calling
getwill cause anExecutionExceptionto be thrown.