gpt4 book ai didi

Java 8 : method reference to a static method in a non-static way

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:43:17 27 4
gpt4 key购买 nike

我正在研究用于 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com