java8函数式接口_java8的函数式接口

函数式接口

就是在java8里允许你为一个接口(只有一个实现的,声明为FunctionalInterface注解的)实现一个匿名的对象,大叔感觉它与.net平台的委托很类似,一个方法里允许你接收一个方法签名,这个方法在一个声明为FunctionalInterface的接口里,并且它是接口里唯一的方法。

java框架里也在用它

在我们的java框架里,很多地方在用函数式接口,下面的线程类的部分代码

@FunctionalInterface

public interface Runnable {

/**

* When an object implementing interface Runnable is used

* to create a thread, starting the thread causes the object's

* run method to be called in that separately executing

* thread.

*

* The general contract of the method run 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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值