函数式接口 Functional Interface
指的是仅仅包含一个抽象方法的接口,可以认为任何一个Lambda 表达式都可以等价转换为对应的函数式接口,可以将任意只包含一个抽象方法的接口用作Lambda 表达式。
使用 @FunctionalInterface 有助于编译器检查函数接口的合法性。
提醒:加不加@FunctionalInterface对于接口是不是函数式接口没有影响,该注解只是提醒编译器去检查该接口是否仅包含一个抽象方法。
Runnable 就是一个函数接口,如下:
// 打印一个换行符
Runable run =() -> System.out.println();
函数式接口用途
它们主要用在Lambda表达式和方法引用(实际上也可认为是Lambda表达式)上。
如定义了一个函数式接口如下:
@FunctionalInterface
interface GreetingService
{
void sayMessage(String message);
}
那么就可以使用Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):
GreetingService greetService1 = message -> System.out.println(“Hello ” + message)
JDK中的函数式接口举例
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object’s
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
任何可以接受一个函数式接口实例的地方,都可以用lambda表达式。
简化的lambda—方法引用(Method Reference)
lambda已经简化了代码的写法,然而方法引用进一步简化了lambda的写法。
方法引用的使用方式:类名::方法名
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!