有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    this::greet指的是一个没有参数也没有返回值的方法。因此,它与Runnable接口的单个方法void run()匹配

    display方法接受Runnable实例。它必须执行Runnablerun方法,才能执行greet方法:

    private  void display(Runnable s) {
        s.run();
        System.out.println("Hello, world!2");
    }
    

    如果将display转换为lambda表达式,则第二次尝试调用它可以通过编译:

    display(()->this.greet());