How to reference a method with exception by using lambda expression
This post would demo how to reference a method with exception by using lambda expression.
- Java 1.8
1. Setup the environment
We have a Enum class Color that represents a color.
2. Reference normal method as lambda expression
And we have a normal color convertor method here:
It just consumes a color string and returns a Color object.
In order to use lambda expression to reference this method, we must use FunctionalInterface ,which is a special type of interface that contains only one abstract method.
We can use the java.util.function.Function to reference this type of method, it consumes something and returns another thing.
@FunctionalInterface public interface Function<T,R>
Represents a function that accepts one argument and produces a result.This is a functional interface whose functional method is apply(Object).
We define a method that accepts a FunctionalInterface like this:
This method accepts a Function<String,Color> and a string, then apply this method on that string.
Then we can reference the getColor method as lambda expression like this:
3. Reference method with exception as lambda expression
But if we have a method that throws an exception like this:
The old code would not compile:
It’s because the java overriding mechanism, you can not throw more exception than the parent. And The java.util.function.Function interface doesn’t throw any exception, so you can not use it to reference a method with exception.
So, we can redefine a new @FunctionalInterface to solve this problem:
And we change the doFunction method as well:
The reference code is the same:
It compiles ok.
In this post we demo the different situations of reference methods as lambda expression. If your method throws an exception, you can define a customized @FunctionalInterface to be compatible.
You can find detail documents about the java lambda here: