方法引用
通过方法的名字来指向一个方法
使用::
引用 , ClassName :: MethodName
说不明白,直接上的代码
Demo
先定义一个类, 创建六个方法
public class Person {
public void eat(){
System.out.println("eat food!");
}
public void study(String s){
System.out.printf("study %s%n", s);
}
public String study2(String s){
return String.format("study %s, 2%n", s);
}
public static void method(){
System.out.println("static method!");
}
public static void method(String s){
System.out.printf("static method! %s%n" , s);
}
public static String method2(String s){
return String.format("static method! %s" , s);
}
}
方法引用示例
final Person person = new Person();
// 非静态方法
// 1. 无参无返回值
final Consumer<Person> eat = Person::eat;
eat.accept(person);
// 2. 有参无返回值
final BiConsumer<Person, String> study = Person::study;
study.accept(person, "English");
// 3. 有参有返回值
final BiFunction<Person, String, String> study2 = Person::study2;
final String english = study2.apply(person, "English");
System.out.println(english);
// 静态方法
// 1. 无参无返回值
final Runnable method = Person::method;
method.run();
// 2. 有参无返回值
final Consumer<String> method2 = Person::method;
method2.accept("2");
// 3. 有参有返回值
final Function<String, String> method21 = Person::method2;
final String haha = method21.apply("haha");
System.out.println(haha);
输出内容
eat food!
study English
study English, 2
static method!
static method! 2
static method! haha
Process finished with exit code 0
使用
了解了方法引用的返回值后,就可以根据需要警醒使用了.
- forEach(Consumer<? super T> action);
参数为一个参数的消费型函数式接口, 就可以使用 Person::eat 了.
Arrays.asList(person,person,person)
.forEach(Person::eat);
总结
通过以上示例,可以看出
::
返回的是函数式接口
- 非静态方法
- 通过方法引用,获取到的是, 对象 + args 的函数式接口
- 静态方法
- 通过方法引用,获取到的是, args 的函数式接口
- 使用
- 可以配合Stream流使用,如:foreach();
- 其他的待探索