函数式接口都可以通过lambda表达式体现,今天写了几个lambda的方法引用场景,特此记录下来。
先上用到的函数式接口:
package com.ces.java8.methodUse;
@FunctionalInterface
public interface InterOne {
void method(int i);
}
package com.ces.java8.methodUse;
@FunctionalInterface
public interface ChangeAbs {
int change(int i);
}
package com.ces.java8.methodUse;
@FunctionalInterface
public interface PrintInter {
void print(String string);
}
package com.ces.java8.methodUse;
@FunctionalInterface
public interface UserFather {
void use();
}
package com.ces.java8.methodUse;
@FunctionalInterface
public interface UseConstruct {
void useCon();
}
package com.ces.java8.methodUse;
@FunctionalInterface
public interface ArrayInter {
int[] build(int arrLength);
}
接下来是测试类的父类和用到的类:
父类:
/**
* @Author xlyu
* @Date 2019/9/27
* @Description
*/
package com.ces.java8.methodUse;
/**
* @program: ces
* @description:
* @author: xlYu
* @create: 2019-09-27 10:11
**/
public class TestFoo {
public void fooMethod(){
System.out.println("this is foo");
}
}
用到的类:
/**
* @Author xlyu
* @Date 2019/9/27
* @Description
*/
package com.ces.java8.methodUse;
/**
* @program: ces
* @description:
* @author: xlYu
* @create: 2019-09-27 09:53
**/
public class TestModel {
public void print(String string) {
String up = string.toUpperCase();
System.out.println(up);
}
}
测试类:
/**
* @Author xlyu
* @Date 2019/9/27
* @Description
*/
package com.ces.java8.methodUse;
/**
* @program: ces
* @description: lambda表达式的方法引用
* @author: xlYu
* @create: 2019-09-27 09:41
**/
public class Test extends TestFoo {
private Test() {
System.out.println("this is Test");
}
private static void method1(int i, InterOne interOne) {
interOne.method(i);
}
private static int toAbs(int i, ChangeAbs changeAbs) {
return changeAbs.change(i);
}
private static void printMethod(PrintInter p) {
p.print("hello");
}
private static void userFather(UserFather userFather) {
userFather.use();
}
private void show() {
userFather(super::fooMethod);
}
private static void useConstruct(UseConstruct useConstruct) {
useConstruct.useCon();
}
private static int[] arr(int length, ArrayInter arrayInter) {
return arrayInter.build(length);
}
public static void main(String[] args) {
//1、动态引用
method1(1, System.out::println);
//2、静态引用
int abs = toAbs(-20, Math::abs);
System.out.println(abs);
//3、对象名引用
TestModel testModel = new TestModel();
printMethod(testModel::print);
//3、父类引用
new Test().show();
//4、构造引用
useConstruct(Test::new);
//5、数组构造引用
int length = 10;
int[] arr = arr(length, int[]::new);
System.out.println(arr.length);
}
}
运行结果:
/**
this is Test
1
20
HELLO
this is Test
this is foo
this is Test
10
*/