当尝试编译表达式时Comparator.comparing(String::toLowerCase)
,Java 编译器返回错误。请参阅以下问题以获取更多信息:
为什么 Comparator.comparing 不适用于 String::toLowerCase 方法引用? https://stackoverflow.com/questions/22936972/why-comparator-comparing-doesnt-work-with-stringtolowercase-method-reference
我已尝试尽可能减少问题。特别是,我已经删除了几乎所有对其他类的依赖关系。这mainmethod 包含两个方法调用。第一个语句编译时没有错误,而第二个语句会产生错误。
interface Fun<T, R> { R apply(T t); }
public final class Foo {
public static void main(String... args) {
invoke(Foo::bar); // OK
invoke(Foo::baz); // ERROR
}
private static <T, U> void invoke(Fun<T, U> f) { }
private String bar() { return null; }
private String baz() { return null; }
private String baz(Integer i, Integer j) { return null; }
}
这很奇怪,因为第二个baz由于参数数量不匹配,该方法不应该适用于这种情况。我看过JLS8(15.13)。然而,这并没有什么帮助,因为方法引用的规则相当复杂。
Q:为什么第二种情况会出现编译错误呢?根据 JLS,真的应该存在编译错误吗?根据其他问题的一些评论,Netbeans中没有编译错误。
作为参考,我使用的是 JDK8 版本 1.8.0-b132。如果在命令行上编译程序,编译器会显示以下错误消息:
$ /opt/jdk8/bin/javac Foo.java
Foo.java:6: error: incompatible types: cannot infer type-variable(s) T,U
invoke(Foo::baz); // ERROR
^
(argument mismatch; invalid method reference
no suitable method found for baz(Object)
method Foo.baz() is not applicable
(actual and formal argument lists differ in length)
method Foo.baz(Integer,Integer) is not applicable
(actual and formal argument lists differ in length))
where T,U are type-variables:
T extends Object declared in method <T,U>invoke(Fun<T,U>)
U extends Object declared in method <T,U>invoke(Fun<T,U>)
Foo.java:6: error: invalid method reference
invoke(Foo::baz); // ERROR
^
non-static method baz() cannot be referenced from a static context
2 errors