什么是函数式接口
所谓的函数式接口,当然首先是一个接口,然后就是在这个接口里面只能有一个抽象方法。
这种类型的接口也称为SAM接口,即Single Abstract Method interfaces
@FunctionalInterface注解
Java 8为函数式接口引入了一个新注解@FunctionalInterface,主要用于编译级错误检查,加上该注解,当你写的接口不符合函数式接口定义的时候,编译器会报错。加不加@FunctionalInterface对于接口是不是函数式接口没有影响,该注解只是提醒编译器去检查该接口是否仅包含一个抽象方法。
public interface GreetingMessage {
public abstract void greet(String name);
}
GreetingMessage就是一个函数式接口。
函数式接口的实现
方式1: 通过实现函数实现
public class Test() {
public static void main(String[] args) {
GreetingMessage gm = new GreetingMessage() {
public void greet(String name) {
System.out.println("Hello " + name);
}
};
gm.greet("Bill");
}
}
Greeting message has an abstract method with no implementation, developer has to add his own every time he creates a new instance of greeting message. This is also known as anoymous in a class. That is all the functional interface is. It allows Java programmers to pass code around as data. At the moment, the codes to implement the functional interface is quite long and messy considering all it does is provide one new line of functionality.
每次都需要新建一个GreetingMessage的实例,该类在Test类中被称为匿名类。
方式2:通过lamda函数实现
public class Test() {
public static void main(String[] args) {
GreetingMessage gm = (String name) -> {
System.out.println("Hello " + name);
};
gm.greet("Bill");
}
}
Lambdas provide a short and simple way to implement functional interfaces in Java. They are now a commonly used feature in the Java language so it is useful to be able to read and understand them, as well as to use them in your own code.
No need to create a new greeting message or write out the whole body the method again.
Lambdas are a quick and simple way of implementing functional interfaces, they look quite different to anonymous inner classes, but the logic is the same and is easy to understand when you are used to reading the syntax.