Why is the compilation of the reference method job?

I am trying to understand why the following code compiles:

public class MethodRefs { public static void main(String[] args) { Function<MethodRefs, String> f; f = MethodRefs::getValueStatic; f = MethodRefs::getValue; } public static String getValueStatic(MethodRefs smt) { return smt.getValue(); } public String getValue() { return "4"; } } 

I see why the first assignment is valid - getValueStatic explicitly matches the specified Function type (it takes a MethodRefs object and returns a String ), but the second one getValue me - the getValue method takes no arguments, so why is it still valid to assign it to f ?

+45
java java-8
Apr 20 '17 at 15:04 on
source share
5 answers

Second

 f = MethodRefs::getValue; 

coincides with

 f = (MethodRefs m) -> m.getValue(); 

For non-static methods, there is always an implicit argument that is represented as this in the called one.

NOTE. The implementation is slightly different at the bytecode level, but it does the same.

+50
Apr 20 '17 at 15:10
source share
β€” -

The non-static method essentially takes the this reference as a special argument. Usually this argument is written in a special way (before the method name, and not in parentheses after it), but the concept is the same. The getValue method takes a MethodRefs object (its this ) and returns a string, so it is compatible with the Function<MethodRefs, String> interface.

+9
Apr 20 '17 at 15:11
source share

Correct it a bit:

 import java.util.function.Function; public class MethodRefs { public static void main(String[] args) { Function<MethodRefs, String> f; final MethodRefs ref = new MethodRefs(); f = MethodRefs::getValueStatic; f.apply(ref); //is equivalent to MethodRefs.getValueStatic(ref); f = MethodRefs::getValue; f.apply(ref); //is now equivalent to ref.getValue(); } public static String getValueStatic(MethodRefs smt) { return smt.getValue(); } public String getValue() { return "4"; } } 
+9
Apr 20 '17 at 15:12
source share

The Java tutorial explains that there are 4 different types of method references:

Your case is # 3, which means that if you have an instance of MethodRef ie ref , calling apply in your function f will be equivalent to String s = ref.getValue() .

+6
Apr 20 '17 at 16:09 on
source share

For non-static methods, this is considered implicit as the first type of argument. Since the type type is MethodRefs , types are checked.

+5
Apr 20 '17 at 15:10
source share



All Articles