In Java, you can refer to an existing method without executing it. This has a specific syntax, and it's called a method reference.
Method references are a great way to pass a method as a parameter or to assign it to a functional interface.
Four Types of Method References
There are multiple types of method references, and each is applied to a different type of method. You'll learn about each in the upcoming sections.
- A method reference to a static method
- A method reference to an instance method of an object of a particular type
- A method reference to an instance method of an existing object
- A method reference to a constructor
How to Write a Method Reference
When it comes to references, you've already been exposed to referencing objects in your code. For example, you've learned how to reference a variable since that is how you pass parameters into methods:
List<String> myList = new ArrayList();
myMethod(myList);
However, when it comes to methods, you can't do the same:
myMethod(someOtherMethod);
The above would cause an error. Thanks to lambda expressions, you can arrive at this functionality!
Syntax
Since Java 8, the :: operator was introduced to provide a reference to a method and essentially use a method as you would an object. The syntax is as follows:
Object :: methodName
Example
In the previous article on lambdas, you learned that lambdas can be used instead of anonymous classes. There are also times when lambdas are simply a reference to another method, for example:
Consumer<String> c = s -> System.out.println(s);
To make the code clearer, you can turn that lambda expression into a method reference:
Consumer<String> c = System.out::println;
When to Use a Method Reference
Now that you've seen how to create a method reference in Java, you might be wondering when you should use one. You might even be thinking that it doesn't seem much clearer, and what happens to the arguments that you would pass into the method?
Well, these are all great questions, and there's a short formula to know whether to use a method reference or not:
If you are thinking of writing an ANONYMOUS CLASS
then better to replace it with a LAMBDA EXPRESSION
and if it calls only one existing method, use a METHOD REFERENCE
As for the rest of your questions, check out the upcoming example page to dive into examples of each one of the four method references to understand how they operate.
Summary: What is a Java Method Reference
- A method reference is used to reference a method without executing it
- The
::operator is used to separate the object and the method name - A method reference can be used when a lambda expression only calls one existing method
Four Types of Method References
- A method reference to a static method
- A method reference to an instance method of an object of a particular type
- A method reference to an instance method of an existing object
- A method reference to a constructor