函数式接口
函数式接口,Functional Interface 是一个有且仅有一个的抽象方法,可以有多个非抽象方法的接口
函数式接口可以被隐式的转换为lambda表达式
1.定义
@FunctionalInterface
interface GreetingService {
void sayMessage(String message);
}
可以用lambda表达式,表示这个GreetingService接口的实现
GreetingService greetService = message -> System.out.println("hello" + message)
2. java8已有的函数式接口
Runnable接口
@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();
}
Callable接口
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
等等
3.函数式接口示例
Predicate
包含多种默认方法,将Predicate组合成其他复杂逻辑
// 定义一个返回Predicate接口的函数,jdk8以前用的是匿名内部类方式,函数里用的是lambda表达式
public Predicate<NotificationContext> isRdsResourcePredicate(){
return c -> delta.api.enums.ResourceType.RDS.getInnerResTypeSet().contains(c.resourceType.getSourceName());
}
// 定义方法判断是否是rds资源
public boolean isRdsResource(NotificationContext context) {
return isRdsResourcePredicate().test(context);
}
原创:做时间的朋友