Java Reference
In-Depth Information
The general syntax for a method reference is
<Qualifier>::<MethodName>
The <Qualifier> depends on the type of the method reference. Two consecutive colons act as a separator.
The <MethodName> is the name of the method. For example, in the method reference String::length , String is the
qualifier and length is the method name.
a method reference does not call the method when it is declared. the method is called later when the method
of its target type is called.
Tip
The syntax for method references allows specifying only the method name. You cannot specify the parameter
types and return type of the method. Recall that a method reference is shorthand for a lambda expression. The target
type, which is always a functional interface, determines the method's details. If the method is an overloaded method,
the compiler will choose the most specific method based on the context. See Table 5-3 .
Table 5-3. Types of Method References
Syntax
Description
TypeName::staticMethod
A method reference to a static method of a class, an interface, or an enum
objectRef::instanceMethod
A method reference to an instance method of the specified object
ClassName::instanceMethod
A method reference to an instance method of an arbitrary object of the
specified class
TypeName.super::instanceMethod
A method reference to an instance method of the supertype of a
particular object
ClassName::new
A constructor reference to the constructor of the specified class
ArrayTypeName::new
An array constructor reference to the constructor of the specified
array type
Using method references may be a little confusing in the beginning. The main point of confusion is the process
of mapping the number and type of arguments in the actual method to the method reference. To help understand the
syntax, I will use a method reference and its equivalent lambda expression in all examples.
Static Method References
A static method reference is used to use a static method of a type as a lambda expression. The type could be a class, an
interface, or an enum. Consider the following static method of the Integer class:
static String toBinaryString(int i)
 
Search WWH ::




Custom Search