此问题已在此处有答案:
Comparator.reversed() does not compile using lambda(4个答案)
2天前关闭。
下面的代码只在情况4下无法编译:
static class Foo {
int seq;
public Foo(int seq) {
this.seq = seq;
}
public int getSeq() {
return this.seq;
}
}
static class Bar<T> {
T seq;
public Bar(T seq) {
this.seq = seq;
}
public T getSeq() {
return this.seq;
}
}
public static void main(String[] args) {
List<Foo> foos = List.of(new Foo(1), new Foo(2));
// case 1 can compile
List<Foo> fooRet1 = foos.stream()
.sorted(Comparator.comparing(Foo::getSeq))
.toList();
// case 2 can compile
List<Foo> fooRet2 = foos.stream()
.sorted(Comparator.comparing(Foo::getSeq).reversed())
.toList();
List<Bar<Integer>> bars = List.of(new Bar<Integer>(1), new Bar<Integer>(2));
// case 3 can compile
List<Bar<Integer>> barRet1 = bars.stream()
.sorted(Comparator.comparing(Bar::getSeq))
.toList();
// case 4 cannot compile
// intellij IDEA draws a red line under Bar::getSeq, it says:
// Non-static method cannot be referenced from a static context
// which is wired
List<Bar<Integer>> barRet2 = bars.stream()
.sorted(Comparator.comparing(Bar::getSeq).reversed())
.toList();
}
这种限制从何而来?
1条答案
按热度按时间6ojccjat1#
这只是Java编译器的一个弱点,它在使用
reversed
时无法推断Bar
的泛型类型。您可以显式添加
Bar
的遗传类型相关问题https://stackoverflow.com/a/25173599/1477418