【发布时间】:2020-02-22 12:29:12
【问题描述】:
刚刚在java中尝试,发现以下问题。
DefaultAndStaticMethodMain.java:8: error: not a statement
implementation1::sendNotification;
^
1 error
以下是我的代码。
父接口:
public interface ParentInterface {
default void callForCompletion() {
System.out.println("<<<< Notification sending completed. >>>>");
}
}
子界面:
public interface ChildInterface extends ParentInterface {
public abstract void sendNotification();
static String printNotificationSentMessage() {
return "Notification is sent successfully.";
}
}
实施 1:
public class Implementation1 implements ChildInterface {
@Override
public void sendNotification() {
System.out.println("Implementation --- 1");
System.out.println("Sending notification via email >>>");
}
}
实施 2:
public class Implementation2 implements ChildInterface {
@Override
public void sendNotification() {
System.out.println("Implementation ---- 2.");
System.out.println("Sending notification via SMS >>>");
}
}
主要方法:
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);
}
}
我不确定自己做错了什么,我在本地机器上安装了 JDK 13,并在 JDK 11 中使用 IntelliJ 2019.3。我检查了 IntelliJ 是否支持 JDK 13
谢谢。
更新 不小心在那边留了一个分号,删掉了,请再检查一下。
【问题讨论】:
-
这不是有效的 Java,即使没有错误的
;。你到底想做什么? -
您打算从自己编写方法引用中发生什么?如果你只写
1 + 1;你也会得到一个错误,因为它不是一个语句并且没有任何效果。错误消息准确地告诉您:error: not a statement. -
可能是奇数个>或
-
“双冒号运算符”? java中没有这样的运算符,它是3.11. Separators-给定的语句无效(就像只有一个变量一样),可能是像
((Runnable) implementation1::sendNotification).run()这样的奇怪,但为什么不直接调用方法? -
或者它可以分配给一个变量/字段:
Runnable r = implementation1::sendNotification;并稍后在r.run();上执行,或者作为参数传递给另一个在那里执行的方法
标签: java