1、概述
大家好,我是欧阳方超。
Java8中引入了不少新特性,其中就包括函数式接口(Functional Interface)和Lambda表达式(Lambda expressions),而理解函数式接口和Lambda表达式是掌握方法引用(Method references)的基础。
方法引用是一种特殊形式的Lambda表达式,使用方法引用可以通过引用现有的方法来创建简单的Lambda表达式。
一共有四种形式的方法引用:
类型 | 方法引用 |
---|---|
静态方法引用 | Class::static_method |
特定对象的实例方法引用 | instance::method |
某个类型的任意对象的实例方法的引用 | Cass::method |
构造方法引用 | Class::new |
下面逐一看一下这几类方法引用的使用。
2、方法引用
2.1、静态方法引用
静态方法引用的语法为,类名::静态方法名,下面是一个使用静态方法引用的例子,方法引用其实是返回了函数式接口InterfaceOne的对象,跟Lambda表达式挺像,只不过方法引用这里所引用的方法名可以跟函数式接口中声明的函数名不同。
@FunctionalInterface
interface InterfaceOne {
void testMethod();
}
class StaticMethod {
public static void staticMethodTest() {
System.out.println("static method test");
}
}
public class MethodReference {
public static void main(String[] args) {
//下面方法引用其实是返回了函数式接口InterfaceOne的对象
InterfaceOne interfaceOne = StaticMethod::staticMethodTest;
interfaceOne.testMethod();
}
}
2.2、实例方法引用
引用实例方法的语法,instance::instanceMethodName,即实例::实例方法名,实例方法引用与静态方法引用很像,只不过一个是通过实例进行引用一个是通过类进行引用。
@FunctionalInterface
interface InterfaceOne {
void testMethod();
}
class StaticMethod {
public void staticMethodTest() {
System.out.println("static method test");
}
}
public class MethodReference {
public static void main(String[] args) {
InterfaceOne interfaceOne = new StaticMethod()::staticMethodTest;
interfaceOne.testMethod();
}
}
2.3、某个类型的任意对象的实例方法的引用
public class MethodReference {
public static void main(String[] args) {
ArrayList<String> lastNames = new ArrayList<>();
lastNames.add("zhang");
lastNames.add("wang");
lastNames.add("li");
Collections.sort(lastNames, String::compareTo);
lastNames.forEach(System.out::println);
}
}
2.4、构造方法引用
构造方法引用的语法,Class::new,
@FunctionalInterface
interface InterfaceOne {
void testMethod();
}
class StaticMethod {
public StaticMethod() {
System.out.println("static method constructor");
}
}
public class MethodReference {
public static void main(String[] args) {
InterfaceOne interfaceOne = StaticMethod::new;
interfaceOne.testMethod();
}
}
3、总结
当想要创建的Lambda体已经有实现方法时,这时可以使用方法引用。Lambda是匿名类的简化写法,方法引用是Lambda的简化写法,如同Lambda表达式创建了函数式接口的实例一样,方法引用也是创建了某个函数式接口的实例。
我是欧阳方超,把事情做好了自然就有兴趣了,如果你喜欢我的文章,欢迎点赞、转发、评论加关注。