A method reference is shorthand to create a lambda expression using an existing method.
If a lambda expression contains a body that is an expression using a method call, you can use a method reference as lambda expression.
Method Reference is a shorthand for writing a lambda expression using an existing method.
The general syntax for a method reference is
<Qualifier>::<MethodName>
For example, String::length, String is the qualifier and length is the method name.
A method reference is called later when its target type is called.
Consider the following code:
ToIntFunction<String> lengthFunction = str -> str.length(); String name = "abcde"; int len = lengthFunction.applyAsInt(name); System.out.println("Name = " + name + ", length = " + len);
The code uses a lambda expression to define an anonymous function that takes a String as an argument and returns its length.
The body of the lambda expression calls the length() method of the String class.
You can rewrite the lambda expression using a method reference to the length() method of the String class, as shown:
ToIntFunction<String> lengthFunction = String::length; String name = "abcde"; int len = lengthFunction.applyAsInt(name); System.out.println("Name = " + name + ", length = " + len);
If the method is an overloaded method, the compiler will choose the most specific method based on the context.
The following table lists the 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 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 |