Junior — Middle
Can you explain what is meant by 'method reference' in programming?
sobes.tech AI
Answer from AI
In Java, a method reference is a way to pass a method as an object that can be invoked later. It is a shortened form of lambda expression, allowing you to refer to an existing method by its name.
Method references come in several types:
- Reference to a static method:
ClassName::staticMethod - Reference to an instance method of a particular object:
instance::instanceMethod - Reference to an instance method of an arbitrary object of a particular type:
ClassName::instanceMethod - Reference to a constructor:
ClassName::new
Example:
import java.util.Arrays;
import java.util.List;
public class MethodReferenceExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
// Using a method reference to print each element
names.forEach(System.out::println);
}
}
Here, System.out::println is a reference to the println method of the System.out object. It is a convenient and readable way to pass behavior to functional interfaces.