JAVA8方法引用

时间:2023-03-09 01:05:36
JAVA8方法引用
方法引用:若Lambda方法体已经实现,我们可以使用方法引用
* 主要有三种语法格式:
* 对象::实例方法名
* 类::实例方法名
* 类::静态方法名
*
* 注意:Lambda体中调用的方法的参数列表与返回值类型,要与函数式中接口的抽象方法的参数列表和返回值类型一样
*
*
* 构造器引用:
* 格式:ClassName::new
*
*
* 数组引用:
* Type :: new
package airycode_java8.nice5;

import airycode_java8.nice1.Employee;
import org.junit.Test; import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier; /**
*
* 方法引用:若Lambda方法体已经实现,我们可以使用方法引用
* 主要有三种语法格式:
* 对象::实例方法名
* 类::实例方法名
* 类::静态方法名
*
* 注意:Lambda体中调用的方法的参数列表与返回值类型,要与函数式中接口的抽象方法的参数列表和返回值类型一样
*
*
* 构造器引用:
* 格式:ClassName::new
*
*
* 数组引用:
* Type :: new
*
*
*
*
* Created by admin on 2019/1/2.
*/
public class TestMethodRef { @Test
public void test1(){
PrintStream ps = System.out;
//Consumer<String> con = (x)-> ps::println;
Consumer<String> consumer = (x)-> ps.println();
// Consumer<String> consumer2 = ps::println;
consumer.accept("aaa");
} @Test
public void test2(){
Employee employee = new Employee();
Supplier<String> supplier = () -> employee.getName();
String str = supplier.get();
System.out.println(str); Supplier<Integer> supplier2 = employee::getAge;
Integer age = supplier2.get();
System.out.println(age); } //静态方法
@Test
public void test3(){ Comparator<Integer> comparator = (x,y)->Integer.compare(x,y); Comparator<Integer> comparator2 = Integer::compare;//方法引用 } //类::实例方法(规则:两个参数,第一个参数是调用方法的实例的调用者(x),第二个参数是实例方法(equals)的参数值(y))
@Test
public void test4(){
BiPredicate<String,String> bp = (x,y)->x.equals(y);
BiPredicate<String,String> bp2 = String::equals;
} //构造器
@Test
public void test5(){
Supplier<Employee> emp = ()->new Employee(); Supplier<Employee> emp2 = Employee::new; Employee employee = emp2.get();
System.out.println(employee);
} //一个参数构造器
@Test
public void test6(){
Function<Integer,Employee> fun = (x)->new Employee(x);
Function<Integer,Employee> fun2 = Employee::new;
Employee employee = fun2.apply(101);
System.out.println(employee.getAge());
} //数组引用
@Test
public void test7(){
Function<Integer,String[]> fun = (x)->new String[x];
String[] arr = fun.apply(10);
System.out.println(arr.length); Function<Integer,String[]> fun2 = String[]::new;
String[] arr2 = fun.apply(20);
System.out.println(arr2.length);
} }