2020-03-04

Lambda expression - Method references

Method references 

Method references are references to existing methods by name. For example, Object::toString references toString method of java.lang.Object class. :: is used to separated class or instance name and method name. Method references are similar with lambda expressions, except that method references don’t have a body, just refer existing methods by name. Method references can be used to remove more boilerplate code. If the body of a lambda expression only contains one line of code to invoke a method, it can be replaced with a method reference.

Functional interface to produce a string
@FunctionalInterface public interface StringProducer { 
String produce(); 
}
StringProducer  is a functional interface with method produce.

This is an example of using StringProducer. displayString method takes an instance of StringProducer and outputs the string to console. In run method, method reference this::toString is used to create an instance of StringProducer. Invoking run method will output text like StringProducerMain@65ab7765 to the console. It’s the same result as invoking toString() method of current StringProducerMain object. Using this::toString is the same as using lambda expression () -> this.toString(), but in a more concise way.

Usage of StringProducer with method reference
public class StringProducerMain { 
public static void main(String[] args) { 
new StringProducerMain().run(); 

public void run() { 
displayString(this::toString); 

public void displayString(StringProducer producer) { 
System.out.println(producer.produce()); 



Types of method references

There are different types of method references depends on the type of methods they refer to.

Static method
Refer to a static method using ClassName::methodName, e.g. String::format, Integer::max.

Instance method of a particular object
Refer to an instance method of a particular object using instanceRef::methodName, e.g.
obj::toString, str::toUpperCase.

Method from superclass
Refer to an instance method of a particular object’s superclass using super::methodName,
e.g. super::toString. In Listing 2.8, if replacing this::toString with super::toString, then
toString of Object class will be invoked instead of toString of StringProducerMain class.

Instance method of an arbitrary object of a particular type
Refer to an instance method of any object of a particular type using ClassName::methodName,
e.g. String::toUpperCase. The syntax is the same as referring a static method. The difference
is that the first parameter of functional interface’s method is the invocation’s receiver.

Class constructor
Refer to a class constructor using ClassName::new, e.g. Date::new.

Array constructor
Refer to an array constructor using TypeName[]::new, e.g. int[]::new, String[]::new.

No comments:

Post a Comment