双冒号运算符不适用于 Java

Bil*_*ins 0 java

只是在java中尝试了一些东西,发现了以下问题。

DefaultAndStaticMethodMain.java:8: error: not a statement
        implementation1::sendNotification;
        ^
1 error
Run Code Online (Sandbox Code Playgroud)

以下是我的代码。

父接口:

public interface ParentInterface {
    default void callForCompletion() {
        System.out.println("<<<< Notification sending completed. >>>>");
    }
}
Run Code Online (Sandbox Code Playgroud)

子界面:

public interface ChildInterface extends ParentInterface {
    public abstract void sendNotification();

    static String printNotificationSentMessage() {
        return "Notification is sent successfully.";
    }
}
Run Code Online (Sandbox Code Playgroud)

实施1:

public class Implementation1 implements ChildInterface {
    @Override
    public void sendNotification() {

        System.out.println("Implementation --- 1");
        System.out.println("Sending notification via email >>>");
    }
}
Run Code Online (Sandbox Code Playgroud)

实施2:

public class Implementation2 implements ChildInterface {
    @Override
    public void sendNotification() {
        System.out.println("Implementation ---- 2.");
        System.out.println("Sending notification via SMS >>>");
    }
}
Run Code Online (Sandbox Code Playgroud)

主要方法:

public class DefaultAndStaticMethodMain {
    public static void main(String[] args) {
        Implementation1 implementation1 = new Implementation1();
        implementation1::sendNotification; // Compilation error as shown above.

        Implementation2 implementation2 = new Implementation2();
        implementation2.sendNotification();

        // Following works fine.
//        Arrays.asList(implementation1, implementation2).stream().forEach(SomeInterfaceToBeRenamed::sendNotification);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不确定我做错了什么,我在本地机器上安装了 JDK 13 并使用带有 JDK 11 的 IntelliJ 2019.3。我检查了 IntelliJ 支持 JDK 13

谢谢。

更新 我错误地在那里留下了一个分号,将其删除,请再次检查。

dim*_*414 5

你打算让这implementation1::sendNotification;条线做什么?经判断implementation2.sendNotification();线下,它看起来像你想叫sendNotificationimplementation1,它是这样写的:

implementation1.sendNotification();
Run Code Online (Sandbox Code Playgroud)

::符号是一个方法引用,并且(如错误消息所述)它是一个标识符,而不是一个语句,因此不能单独成为一行。同样,您不能将implementation1;(变量)或ChildInterface;(类标识符)写为语句。

.forEach(SomeInterfaceToBeRenamed::sendNotification);行编译是因为您将方法引用传递给forEach(),并且依次调用每个sendNotification()方法。


MC *_*ror 5

方法引用与方法调用不同。这是两个截然不同的东西。

  • 方法调用是一个独立的表达式,或者更准确地说,是一个表达式语句。这意味着在您的情况下implementation2.sendNotification(),正如您所期望的那样。

  • 然而,一个方法参考,

    用于指不实际执行调用的方法的调用

    并且不是一个独立的表达式。它只能用于也可以使用 lambda 表达式的地方。作为独立表达式的方法引用不会编译,就像没有赋值的算术表达式(例如3 + 17;)。这是由 Java 语言规范§ 14.8§ 15.13强制执行的。


更多阅读: