我正在研究用于 OCP 考试的新 Stream API,我发现了一些我不太理解的东西。这是我的代码:
void methodOne() {
this.compare(1, 2); // This works fine.
Stream.of(1,2,3)
.sorted(this::compare); // Compilation error.
}
static Integer compare(Integer s1, Integer s2) {
return 0;
}
这里我有一个名为 compare 的静态方法和一个名为 compare 的非静态方法。如果我从非静态方法调用比较方法,我会收到编译器警告:
The method compare(Integer, Integer) from the type TestStream should be accessed in a static way
如果我改为在我的流中使用对同一方法的方法引用,则该编译器警告将变成具有相同消息的编译器错误。
我知道为什么会收到警告,但我不明白为什么如果我使用方法引用,此警告会变成编译错误。我也没有在网上找到任何东西。有人可以向我解释吗?
最佳答案
迄今为止,通过引用访问静态方法被视为设计错误。你甚至可以这样做:
YourClass c = null;
c.compare (...)
那会工作得很好(虽然有警告)。
当 java-8 特性设计时这个问题被纠正了,所以访问静态方法(对于方法引用)的唯一方法是通过类本身:
YourClass::compare
关于Java 8 : method reference to a static method in a non-static way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50872669/