双冒号运算符语法,类名/对象名::方法名
静态方法的引用,引用该对象的方法,不赋值,做相应的操作:
public class demo {
public static void buildData(String data){
System.out.println(data);
}
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(demo::buildData);
}
}
实例方法的引用:
public class demo {
public static void main(String[] args) {
Runnable runnable = () -> buildData("ancen", "ancen2");
runnable.run();
Runnable runnable1 = demo::noParamsRequired;
}
//需要调用带参数的
public static void buildData(String value, String value2) {
System.out.println(value + value2);
}
//不需要调用的参数
public static void noParamsRequired() {
System.out.println("no params required");
}
}
构造函数的引用:
@Data
class Student {
private Integer id;
private String name;
private String desc;
public Student(String string) {
System.out.println(string);
}
}
public class demo {
public static void main(String[] args) {
//studentFunction是Function类型的函数接口,接收一个字符串String,并返回Student对象
Function<String,Student> studentFunction = Student::new;
//通过方法构造一个Student对象
Student student = studentFunction.apply("ancen");
}
}