在Java中,双冒号(::)用于方法引用表达式(Method Reference Expressions)。
方法引用表达式指向一个方法的调用但实际又没有真正立即执行调用。将方法引用表达式赋值给一个功能函数。
方法引用表达式可以引用类的静态方法(类方法)、非静态方法(类实例方法)、类的创建,数组的创建。
https://docs.oracle.com/javase/specs/jls/se20/html/jls-15.html#jls-15.13
代码示例:
package com.thb;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class Test2 {
public static void main(String[] args) {
// 将类实例方法(即非静态方法)引用赋值给功能函数
Function<String, String> fun1 = String::toUpperCase;
System.out.println(fun1.apply("very good"));
// 将类方法(即静态方法)引用赋值给功能函数
Supplier<Long> fun2 = System::currentTimeMillis;
System.out.println(fun2.get());
// 将数组创建引用赋值给功能函数
Function<List<String>, ArrayList<String>> fun3 = ArrayList<String>::new;
System.out.println(fun3.apply(Arrays.asList("hello", "world")));
// 将类实例创建引用赋值给功能函数
Supplier<Date> fun4 = Date::new;
System.out.println(fun4.get().toString());
}
}
运行结果: