Java8 Functional Interface
1 函数式接口
函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
1.1 函数式接口可以被隐式转换为lambda表达式;
1.2 函数式接口可以现有的函数友好地支持 lambda;
1.3 确保函数式接口符合语法,可以添加@FunctionalInterface注解;
/**
* java8 interface add default and static method
*/
@FunctionalInterface
public interface FuncInterface {
//common sbstract method
public void reference();
//interface default method
default void defaultMehtod() {
System.out.println("This is a default method~");
}
//interface second default method
default void anotherDefaultMehtod() {
System.out.println("This is the second default method~");
}
//interface static method
static void staticMethod() {
System.out.println("This is a static method~");
}
//interface second static method
default void anotherStaticMethod() {
System.out.println("This is the second static method~");
}
}
Java8中会经常用到的函数式接口:
java.awt.event.ActionListener;
java.lang.Runnable
java.util.concurrent.Callable
java.security.PrivilegedAction
java.util.Comparator
java.io.FileFilter
java.beans.PropertyChangeListener
2 java.util.function包
Java 8添加一个新的包”java.util.function”,通常用于lambda表达式和方法引用,包下有很多通用接口,当通用接口可以满足你的时候,就不需要自己建了。
//函数式接口
@FunctionalInterface
public interface FuncInterface {
//common sbstract method
public String reference();
}
这个接口就可以用java.util.function包下的Supplier接口来代替,这个接口包含了T get()方法可以与String reference()等效:
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
使用场景:
FuncInterface funcInterface = new FuncInterface() {
@Override
public String reference() {
return "funcInterface,你找到了我,哈哈~";
}
};
String reference = funcInterface.reference();
System.out.println("reference-->" + reference);
Supplier接口也可以实现:
Supplier supplier = () -> {
return "supplier,你找到了我,哈哈~";
};
Object str = supplier.get();
System.out.println("str-->" + str.toString());
结果:
reference-->funcInterface,你找到了我,哈哈~
str-->supplier,你找到了我,哈哈~
涉及代码:–>GitHub
参考文献:
[ 1 ] http://java8.in/java-8-lambda-expression/
[ 2 ] https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach6
[ 3 ] https://winterbe.com/posts/2014/03/16/java-8-tutorial/