FunctionalInterface
我们把只定义了单方法的接口称之为FunctionalInterface
,用注解@FunctionalInterface
标记。例如,Callable
接口:
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
再来看Comparator
接口:
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
default Comparator<T> reversed() {
return Collections.reverseOrder(this);
}
default Comparator<T> thenComparing(Comparator<? super T> other) {
...
}
...
}
虽然Comparator
接口有很多方法,但只有一个抽象方法int compare(T o1, T o2)
,其他的方法都是default
方法或static
方法。另外注意到boolean equals(Object obj)
是Object
定义的方法,不算在接口方法内。因此,Comparator
也是一个FunctionalInterface
。
简单示例
定义一个Hello的接口:
@FunctionalInterface
public interface Hello {
String msg(String info);
}
调用执行示例:
Hello hello = param -> param + "world!";
System.out.println("test functional:" + hello.msg("hello,"));
则输出为:
test functional:hello,world!
从上述的代码中可以发现,核心点在于->前后的内容,基于->声明了一个功能函数FunctionalInterface,这可以在代码中直接进行调用。
本质上是将函数的实现直接转换为了一个声明语句的定义,极大简化了原有的实现方式。又有的实现方式是什么呢,下面来看一下:
Hello hello2 = new Hello() {
@Override
public String msg(String info) {
return info + ",world";
}
};
相比来看,是否变得简单了一些?