Invalid method reference for overloaded method with different arities

帅比萌擦擦* 提交于 2019-12-04 06:17:59

JLS8 (15.13) is confusing but it does show examples similar to yours stating their are ambiguities in searching that it cannot resolve.

For your example Intellij says invoke(Foo::baz); is a Cyclic inference which I think has more to do with the combination of invoke needing to inferred a type as well as Foo::baz.

This can be resolved by giving a type to the invoke function, similar to JSL (15.13.1 examples)

The search is smart enough to ignore ambiguities in which all the applicable methods (from both searches) are instance methods:

Foo.<Foo,String>invoke(Foo::baz); -- equivalent to, I want to use the void method of Foo that returns a String aka String baz()

interface Fun<T, R> { R apply(T t); }
interface Fun2<T,U,R> { R apply(T t, U u); }

public final class Foo {
    public static void main(String... args) {
        invoke(Foo::bar); // OK
        Foo.<Foo,String>invoke(Foo::baz); // NO ERROR
        Fun2<Foo, Integer, String> f2 = Foo::baz; // Overloaded method baz
    }
    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) { return null; } 
}

I do agree with you that baz(Integer i) is not a valid argument to invoke with out making it static or from an instance of Foo. I guess the search algorithm just quits if the method is overloaded and it is trying to infer the type. Because it does work with just a single method signature.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!