方法引用的五种方式
- 引用对象的实例方法 对象::实例方法名
- 引用类的静态方法 类::静态方法名
- 引用类的实例方法 类::实例方法名
- 引用构造方法 类::new
- 数组引用 类型::new
方法引用示例
/**
*要使用的对象
*/
public class Human{
private String name;
public Human(){
}
public Human(String name){
this.name = name;
}
public static String getNationality(){
return "中国";
}
public String getName(){
return name;
}
public void setName(String name){
this.name =name;
}
}
Human human = new Human("赵云");
/**
*引用对象的实例方法
*/
//使用Lambda表达式
Supplier<String> sup2=human.getname();
System.out.println(sup1.get());
//使用方法引用
Supplier<String> sup2 = human::getName;
System.out.println(sup2.get());
/*
*引用类的静态方法
*/
//使用Lambda表达式
Supplier<String> sup3 = ()-> Human.getNationality();
System.out.println(sup3.get());
//使用方法引用
Supplier<String> sup4 = Human::getNationality;
System.out.println(sup4.get()):
/*
*引用类的实例方法名
*/
Human human2 = new Human("张飞");
//使用Lambda表达式
Function<Human,String> function1 = p->p.getName();
System.out.println(function1.apply(human2));
//使用方法引用
Function<Human,String> function2 = Human::getName;
System.out.println(function2.apply(human2));
/*
*引用构造方法
*/
//使用Lambda表达式
Supplier<Human> supplier1=()->new Human("貂蝉");
System.out.println(supplier2.get() instanceof Human);//true
//使用方法引用带参构造
Function<Sting,Human> func3 = Human::new;
System.out.println(func3.apply("吕布").getName());
/**
*引用数组
*/
//使用Lambda表达式
Function<Integer,Integer[]> func4 = x->new Integer[]{x};
//添加数组的元素,并输出数组长度
System.out.println(func4.apply(4).length);
//使用方法引用数组
Function<Integer,Integer[]> func5 = Integer[]::new;
//生成11个长度的数组
System.out.println(func5.apply(11).length);