The oracle Java 8 documentation defines 4 types of method references you can use instead of Lambda Expressions. What I am trying to understand is the kind of method reference described as: "Reference to an instance method of an arbitrary object of a particular type " which is written as ContainingType::methodName
.
I am not sure if I am missing something, but to me it seems more like:
"Reference to the first parameter of the abstract method of the Functional Interface, assuming it is of type ContainingType
". I tried to come up with examples where this 'arbitrary object' is the second parameter, but of course it does not compile.
Is there an official reference how this object is resolved by the compiler? Am I correct in my understanding that:
So a functional interface with abstract method A method(B b, C c, D d)
can only be passed instance method references x::methodImpl
or B::methodImpl
. There is no way I can pass C::methodImpl
for example, where it would be an instance of class C
with its signature A methodImpl(B b, D d)
.
Are there any other cases I am missing, which might be the reason why Oracle wrote this in such an ambiguous way?
So the syntax for a reference to an instance method of an arbitrary object of a particular type is "ContainingType::methodName".
To make the code clearer, you can turn that lambda expression into a method reference: Consumer<String> c = System. out::println; In a method reference, you place the object (or class) that contains the method before the :: operator and the name of the method after it without arguments.
References to static methods A static method reference refers to a static method in a specific class. Its syntax is className::staticMethodName , where className identifies the class and staticMethodName identifies the static method. An example is Integer::bitCount .
No, your understanding is correct. The documentation you linked implies (but does not adequately emphasize) that given a functional interface that expects args a1, a2, a3, ...
, a method reference of this type is equivalent to a lambda that calls a1.namedMethod(a2, a3, ...)
.
Note that a concrete definition like this is required for consistency's sake - given the example on the linked documentation of a functional interface with two String
arguments (String s1, String s2)
, how would you determine whether the behavior would be s1.doThing(s2)
or s2.doThing(s1)
otherwise?
You can find this specified precisely in the JLS:
If the compile-time declaration is an instance method, then the arguments to the method invocation expression (if any) are the second and subsequent formal parameters of the invocation method. Otherwise, the arguments to the method invocation expression are the formal parameters of the invocation method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With