r/javahelp • u/[deleted] • Feb 03 '20
Syntactic sugar: static references to instance methods?
Hello!
I found the following thing a little bit strange. Consider the following class:
class Example{
public void foo(int x){
}
public void bar(){
}
}Now I can make an object, get a method reference to an instance method and then use it.
Example e = new Example();
Consumer<Integer> ex = e::foo;
ex.accept(4);Method foo(int x) is clearly a Consumer<Integer>. How ever, I have no idea why the following works:
Consumer<Example> ex2 = Example::bar;
ex2.accept(new Example()); First, it refers to Example::bar in a static way, even though it is an instance method.
Secondly, Consumer<Example> means it consumes Example -objects, which implies there is a method accept(Example e). But Example::bar is clearly not a Consumer<Example>
I guess the
Consumer<Example> a = Example::bar; is translated to following:
Consumer<Example> a = (x) -> x.bar();I could not find this anywhere in the tutorial or any other article that would explain it. I'd think that if syntactic sugar like this exists, where's the documentation?
10
u/GuyWithLag Feb 03 '20
No; it is a method reference expression which refers to the set of methods named
barin theExampleclass. Now, there are some applicability schenanigans that I'm not smart enough to explain, but the gist is that the reference is converted to the target type given by the assignment, and one of the criteria is the number of arguments used to filter the set of potential methods; in the JLS is stated thatSo, it's looking at both static and non-static methods. Further down the text:
So, non-static methods get converted to a lambda that has an extra parameters that acts as
this(in the context of the virtual lambda expression that is created for that method reference).