- 自定义函数型接口
- 函数型接口作为方法入参的使用
- 类名::类方法在函数型接口中的使用
public interface TestFunction {
/**
* 函数型接口的使用
*/
static void main(String[] args) {
System.out.println("----------1----------");
test01(TestFunction::method01);
test01(()-> System.out.println("test01-hello"));
System.out.println("----------2----------");
System.out.println(test02(TestFunction::method02));
System.out.println(test02(() -> "test02-hello"));
System.out.println("----------3----------");
System.out.println(test03(1,TestFunction::method03));
System.out.println(test03(0,(Integer x) -> x == 0 ? "zero":"not zero"));
System.out.println(test03_01(0, x -> x == 0 ? "zero":"not zero"));
System.out.println("----------4----------");
System.out.println(test04((x,y,z) -> x * y + z ));
System.out.println(test04(6,8,9,(Integer x,Integer y, Integer z) -> x * y + z ));
}
//自定义函数型接口
@FunctionalInterface
interface Test01Function { void get();}
@FunctionalInterface
interface Test02Function<X,Y,Z>{ void get(X x, Y y, Z z);}
@FunctionalInterface
interface Test03Function<X,Y,Z,M>{ M get(X x, Y y, Z z);}
static void test01(Test01Function function){
function.get();
}
static <T> T test02(Supplier<T> function){
return function.get();
}
static <T,R> R test03(T param, Function<T,R> function){
return function.apply(param);
}
static String test03_01(Integer param, Function<Integer,String> function){
return function.apply(param);
}
static int test04(Test03Function<Integer,Integer,Integer,Integer> function){
int x = 3 , y= 2 , z = 5;
return function.get(x,y,z);
}
static<X,Y,Z,M> M test04(X x , Y y , Z z, Test03Function<X,Y,Z,M> function){
return function.get(x,y,z);
}
static void method01(){
System.out.println("method01");
}
static String method02(){
return "method02";
}
static String method03(Integer i){
if (i == 0){
return "zero";
} else {
return "not zero";
}
}
}
控制台输出
----------1----------
method01
test01-hello
----------2----------
method02
test02-hello
----------3----------
not zero
zero
zero
----------4----------
11
57
Process finished with exit code 0