
2.4 方法引用
我们可以使用已有的方法定义方法引用,并像Lambda表达式一样,把方法引用作为方法的参数使用。在Java中,方法引用使用“::”(两个冒号)表示。
2.4.1 构造器方法引用
构造器方法引用使用“类名::new”来定义。
◎无参数构造:构造器不接收参数,返回值为新建的Person对象,符合Supplier函数接口的定义。使用基于Lambda表达式的Supplier函数接口的实现与“方法引用”是等同的。

◎一个参数构造:构造器接收一个参数,返回值为新建的Person对象,符合Function接口的定义。同样,使用基于Lambda表达式的Function接口实现与方法引用是等同的。

◎两个参数构造:构造器接收两个参数,返回值为新建的Person对象,符合BiFunction接口的定义。同样,使用基于Lambda表达式的BiFunction接口实现与方法引用是等同的。

◎三个参数构造:构造器接收三个参数,返回值为新建的Person对象,符合我们自定义的TriFunction接口的定义。同样,使用基于Lambda表达式的TriFunction接口实现与方法引用是等同的。

2.4.2 静态方法引用
静态方法引用是使用方法引用的方式调用类的静态方法,格式为“类名::静态方法”。

a.Integer::toString,toString方法是Integer类型的静态方法,toString方法的参数和返回值符合IntFunction接口的定义。
b.Lambda表达式,等同于上一句。
2.4.3 实例方法引用
实例方法引用是使用方法引用的方式来调用实例对象的方法,格式为“实例对象名::实例方法”。

walk方法是Person类实例对象方法。

2.4.4 引用特定类的任意对象的方法
引用特定类的任意对象的方法的格式为“类型名::实例方法”。

此处的sayName方法是实例对象方法,people列表里的三个Person实例均可以调用这个方法。注意和上面“实例方法引用”的区别,“实例方法引用”只针对一个实例对象进行方法引用,而当前的“引用特定类的任意对象的方法”可以对people列表里的任意Person实例对象进行方法引用。sayName方法是Person类的方法。

从上面4种方法引用与Lambda表达式的对比可以知道,在调用现有类的已有方法时,方法引用比Lambda表达式更自然,可读性更强。比如上面的例子。

可以用方法引用改写成下面的样子。
