Functional 是什么
函数式接口,首先是一个接口,这个接口里面只能有一个抽象方法。
这种类型的接口也称为SAM接口,即Single Abstract Method interfaces
特点
- 接口有且仅有一个抽象方法
- 允许定义静态方法
- 允许定义默认方法
- 允许java.lang.Object中的public方法
- 该注解不是必须的,如果一个接口符合"函数式接口"定义,
那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。
如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错
简单例子
@FunctionalInterface
public interface TestInterface {
int add(int a,int b);
}
@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();
}
public class FunctionalInterfaceTest {
@Test
public void test1(){
TestInterface testInterface = (a,b) -> a+b;
int result = testInterface.add(1,2);
System.out.println(result);
// 等于如下写法,但是上面看起来更简洁
TestInterface testInterface1 = new TestInterface() {
@Override
public int add(int a, int b) {
return a+b;
}
};
int result1 = testInterface1.add(1,2);
System.out.println(result1);
}
@Test
public void test2(){
Runnable runnable = ()-> System.out.println(111);
Runnable runnable2 = ()->{
System.out.println(2222);
System.out.println(222);
};
runnable.run();
runnable2.run();
}
}
JDK中的函数式接口举例
java.lang.Runnable,
java.util.Comparator,
java.util.concurrent.Callable
java.util.function包下的接口,如Consumer、Predicate、Supplier等
参考:
https://www.jianshu.com/p/52cdc402fb5d
https://blog.csdn.net/aitangyong/article/details/54137067