0

The following code is a common construct used with spring framework. The purpose it to provide configuration class that itself provides the required implementation classes, here AsyncUncaughtExceptionHandler.

Is it possible/advisable to refactor this code using the new java 1.8 lambda expressions? If yes, how?

@Component
public class AsyncConfigurer extends AsyncConfigurerSupport {
    @Autowired
    private CustomService service;

    @Autowired
    private Logger logger;

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                service.call();
                logger.fatal(ex);
            }
        };
    }
}
7
  • I would recommend to use a lambda for readability, not for optimization. I am not even sure that it will not provide exactly the same bytecode. Commented Mar 23, 2015 at 14:20
  • I think this is mainly a question of "style". People working a lot with Java 8 lambdas will tell you to change this code; people who don't like this new feature might ask you to not do it. My personal recommendation: go and ask those people that will be working with this code in the future. One reason for not porting: are you sure that you will never ever have to recompile your code with JDKs prior 1.8? Commented Mar 23, 2015 at 14:21
  • We, ok thanks for your opinion. Let me rephrase my question: how could lambda be used to refactor the above code? How would it look like? (as I could not find any examples regarding such types of code constructs). Commented Mar 23, 2015 at 14:23
  • @Sotirios Delimanolis I don't think this is a duplicate, as your linked question is about FunctionalInterfaces, which mine is NOT about! Commented Mar 23, 2015 at 14:39
  • 1
    AsyncUncaughtExceptionHandler is a functional interface, otherwise the answer provided by Duncan (and the duplicate) would not work. Commented Mar 23, 2015 at 14:39

1 Answer 1

4

Whether you want to do this is up to you; it's mostly a matter of style.

If you did, it would look like this:

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  return (ex, method, params) -> {
    service.call();
    logger.fatal(ex);
  };
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.