1. 概念
-
方法引用就是给一个方法设置别名,相当于一个方法定义了不同的名字。
-
方法引用在Java8中共定义了4中形式
- 引用静态方法: 类名称::static方法名称
- 引用某个对象的方法: 实例化对象::普通方法
- 引用特定类的方法: 特定类::方法
- 引用构造方法: 类名称::new
2. 引用静态方法
- 在String类中有valueOf()方法
/** * 实现方法的引用接口 * @param引用方法的参数类型 * @param
引用方法的返回值类型 */@FunctionalInterfaceinterface IMessage3 { R zhuanhuan(P p);}public class MethodReferenceDemo1 { public static void main(String... args) { // 将String.valueOf()方法变为了IMessage接口里的zhuanhuan()方法 IMessage3 msg = String :: valueOf; String str = msg.zhuanhuan(1000); System.out.println(str.replaceAll("0", "9")); }}
3. 普通方法引用
/** * 实现方法的引用接口 * @param引用方法的返回值类型 */@FunctionalInterfaceinterface IMessage3 { R upper();}public class MethodReferenceDemo1 { public static void main(String... args) { IMessage3 msg = "hello" :: toUpperCase; String str = msg.upper(); System.out.println(str); }}
4. 特定类对象引用
- 需要特定类的对象支持
- String类中的compareTo
@FunctionalInterfaceinterface IMessage3{ int compare(P p1, P p2);}public class MethodReferenceDemo1 { public static void main(String... args) { IMessage3
msg = String :: compareTo; System.out.println(msg.compare("A", "B")); }}
- 与此前相比,方法引用前不需要定义对象,而是可以理解为将对象定义在了参数上
5. 引用构造方法
@FunctionalInterfaceinterface IMessage3{ C create(String t, double p);}class Book { private String title; private double price; public Book(String title, double price) { this.title = title; this.price = price; } @Override public String toString() { return "书名: " + this.title + ", 价格: " + this.price; }}public class MethodReferenceDemo1 { public static void main(String... args) { IMessage3 msg = Book :: new; // 引用构造方法 Book book = msg.create("Java开发", 20.22); System.out.println(book.toString()); }}