I have come across a use of Java Method Reference which I don't know how it can be compiled and executed successfully.
I have the following @FunctionalInterface
:
@FunctionalInterface
public interface NotifyFunction {
void notify(NotifyService notifyService, String message, int target);
}
The NotifyService
is an interface which has some methods:
public interface NotifyService {
public void notifyOne(String message, int target);
public void notifyTwo(String message, int target);
}
public class ConsoleNotifyService implements NotifyService {
public void notifyOne(String message, int target) {
System.out.println("[ONE] " + message + target);
}
public void notifyTwo(String message, int target) {
System.out.println("[TWO] " + message + target);
}
}
I add an enum
for containing all the strategies:
public enum NotifyStrategy {
// HOW???
ONE(NotifyService::notifyOne),
TWO(NotifyService::notifyTwo);
private final NotifyFunction notifyFunction;
NotifyStrategy(NotifyFunction notifyFunction) {
this.notifyFunction = notifyFunction;
}
public void notify(NotifyService notifyService) {
this.notifyFunction.notify(notifyService, "TEST", new java.util.Random().nextInt());
}
}
I don't understand how Java can convert from NotifyService::notifyOne
to an instance of NotifyFunction
when:
(1) The method signatures do not match.
(2) NotifyService::notifyOne
is a reference to an interface.
The following main
works correctly:
public static void main(String... args) {
NotifyStrategy.ONE.notify(new ConsoleNotifyService());
NotifyStrategy.TWO.notify(new ConsoleNotifyService());
}