java这个::instanceMethod在java8中用作方法参数有什么用途
我刚开始学习java8流api。我见过一个方法,它有输入类型Runnable
接口,甚至允许将this::greet
作为参数传递。当程序运行时,为什么不调用greet方法?它的输出只有Hello, world!2
。为什么即使输入是可运行的接口,它也允许传递这样的方法
public class TestAnno {
public static void main(String[] args) {
TestAnno anno=new TestAnno();
}
public TestAnno() {
display(this::greet); // what is use of calling this method
display(this.greet()); //compiler error: The method display(Runnable) in the type TestAnno is not applicable for the arguments (void)
}
private void display(Runnable s) {
System.out.println("Hello, world!2");
//Arrays.sort(new String[]{"1","2"}, String::compareToIgnoreCase);
}
public void greet() {
System.out.println("Hello, world! greet");
}
}
我创建了界面来理解它
public interface Inter1 {
void hello();
void hello1(int a);
}
现在我将display method param改为Inter1
,而不是Runnable
。它抛出错误“此表达式的目标类型必须是函数接口”
就像
public class TestAnno {
public static void main(String[] args) {
TestAnno anno=new TestAnno();
}
public TestAnno() {
display(this::greet); // The method display(Inter1) in the type TestAnno is not applicable for the arguments (this::greet)
display(()->this.greet());//The target type of this expression must be a functional interface
}
/*private void display(Runnable s) {
System.out.println("Hello, world!2");
Arrays.sort(new String[]{"1","2"}, String::compareToIgnoreCase);
}*/
private void display(Inter1 s){
}
public void greet() {
System.out.println("Hello, world! greet");
}
}
谁能帮上忙
# 1 楼答案
this::greet
指的是一个没有参数也没有返回值的方法。因此,它与Runnable
接口的单个方法void run()
匹配display方法接受
Runnable
实例。它必须执行Runnable
的run
方法,才能执行greet
方法:如果将
display
转换为lambda表达式,则第二次尝试调用它可以通过编译: