java8的函數式接口
函數式接口
就是在java8里允許你為一個接口(只有一個實現的,聲明為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();
}
浙公網安備 33010602011771號