Instance Method References on a Specific Instance
Capture a specific object and reference one of its instance methods for callbacks and listeners.
Specific Instance Reference
An instance method reference on a specific instance captures a particular object and references one of its methods. Syntax: instance::methodName.
// System.out is a specific PrintStream instance
List<String> names = List.of("Alice","Bob","Carol");
names.forEach(System.out::println); // System.out is the captured instanceCapturing a Custom Object Instance
Any object can be captured. The method reference borrows the instance at the time of creation:
class Greeter {
private String prefix;
Greeter(String prefix) { this.prefix = prefix; }
String greet(String name) { return prefix + ", " + name + "!"; }
}
Greeter g = new Greeter("Hello");
java.util.function.Function<String, String> greetFn = g::greet;
System.out.println(greetFn.apply("Alice")); // Hello, Alice!
System.out.println(greetFn.apply("Bob")); // Hello, Bob!All lessons in this course
- Static Method References
- Instance Method References on a Specific Instance
- Arbitrary-Instance Method References
- Constructor References