方法引用-通过this引用成员方法和类的构造器引用以及数组的构造器引用
通过this引用成员方法
this代表当前对象 如果需要引用的方法就是当前类中的成员方法 那么可以使用this::成员方法 的格式来使用方法引用
函数式接口:
public interface Richanle { void buy(); }
测试类:
public class Husband { //重写父类的成员方法 public void buyHouse() { System.out.println("在北京四环內买一套房"); } //定义一个方法,参数传递接口 public void men(Richanle r){ r.buy(); } public void show(){ /* 调用本类的方法 */ men(()->{ this.buyHouse(); }); /* 使用Lambda表达式优化代码 */ men(this::buyHouse); } public static void main(String[] args) { new Husband().show(); } }
类的构造器引用
由于构造器的名称与类名完全一样 并不固定 所以构造器引用使用类名称::new的格式表示
函数接口:
public interface PersonBuilbr { Person buile(String name); }
测试类:
/* 类的构造器(构造方法)引用 */ public class Demo { //定义一个方法 参数传递姓名和PersonBuilder接口 方法中通过姓名创建Person对象 public static void printName(String name,PersonBuilbr builbr){ Person buile = builbr.buile(name); System.out.println(buile.getName()); } public static void main(String[] args) { //调用printName方法 方法的参数PersonBuilder接口是一个函数式接口 可以传递Lambda printName("迪丽热巴", (String name)->{ return new Person(name); }); /* 使用方法引用优化Lambda表达式 构造方法new Person(String nane)已知 创建对象已知 new 就可以使用Person引用new创建对象 */ printName("古力娜扎",Person::new);//通过Person类的带参构造方法,通过传递的姓名创建对象 } }
运行结果:

数组的构造器引用
数组也是Object 的子类对象,所以同样具有构造器,只是语法稍有不同。如果对应到Lambda的使用场景中时,
函数式接口:
/* 定义一个创建数组的函数式接口 */ public interface ArrayBuilder { //定义一个int类型数组的方法,参数传递数组的长度,返回创建好的int类型数组 int[] builderArray(int lenth); }
测试类:
/* 数组的构造器引用 */ public class Demo { /* 定义一个方法 */ public static int[] l(int leng,ArrayBuilder a){ return a.builderArray(leng);//创建数组并返回 } public static void main(String[] args) { int[] a= l(10, (k)->{ //根据数组的长度,创建数组并返回 return new int[k]; }); System.out.println(a.length); //使用方法引用优化Lambda表达式 int[] l = l(10, int[]::new); System.out.println(Arrays.toString(l));//查看数组内容 System.out.println(l.length); } }
运行结果:


浙公网安备 33010602011771号