内容简介:就是在java8里允许你为一个接口(只有一个实现的,声明为FunctionalInterface注解的)实现一个匿名的对象,大叔感觉它与.net平台的委托很类似,一个方法里允许你接收一个方法签名,这个方法在一个声明为FunctionalInterface的接口里,并且它是接口里唯一的方法。在我们的java框架里,很多地方在用函数式接口,下面的线程类的部分代码事实上,在外部需要使用Runnable的实例时,可以直接构建一个匿名对象,像下面的代码是合法的
函数式接口
就是在 java 8里允许你为一个接口(只有一个实现的,声明为FunctionalInterface注解的)实现一个匿名的对象,大叔感觉它与.net平台的委托很类似,一个方法里允许你接收一个方法签名,这个方法在一个声明为FunctionalInterface的接口里,并且它是接口里唯一的方法。
java框架里也在用它
在我们的java框架里,很多地方在用函数式接口,下面的线程类的部分代码
@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();
}
事实上,在外部需要使用Runnable的实例时,可以直接构建一个匿名对象,像下面的代码是合法的
super.periodicCheck(new PassableRunnable() {
private boolean passed = false;
@Override
public boolean isPassed() {
return passed;
}
@Override
public void run() {
System.out.println("test async task");
passed = true;
}
});
下面是大叔在单元测试里写的一段实例代码,供大家学习和参考
@Test
public void testMethodFunction() {
java8Fun(new Run() {
@Override
public void print() {
System.out.println("类似.net里的委托!");
}
});
}
public void java8Fun(Run run) {
System.out.println("执行java8函数式接口");
run.print();
}
@FunctionalInterface
interface Run {
void print();
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Java8 函数接口
- 深入理解 lambda表达式 与 函数式编程 函数式接口源码解析(二)
- Go指南-谈谈Go的接口与函数
- 用 Go 开发接口服务--公共类关键函数
- Java8新特性学习-函数式接口
- 用 Go 开发接口服务--灵活写 Dao 数据层函数
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Beginning iPhone and iPad Web Apps
Chris Apers、Daniel Paterson / Apress / 2010-12-15 / USD 39.99
It seems that everyone and her sister has developed an iPhone App—everyone except you, the hard-working web professional. And now with the introduction of the iPad, you may even feel farther behind. B......一起来看看 《Beginning iPhone and iPad Web Apps》 这本书的介绍吧!
在线进制转换器
各进制数互转换器
UNIX 时间戳转换
UNIX 时间戳转换