java @FunctionalInterface

时间:2024-10-10 17:33:20
public class Worker {
private String doWork(String job) {
return "Job " + job + " done.";
} private void handleWork(Handler<String, String> theFuncHandler) {
System.out.println(theFuncHandler.handle("job-" + System.currentTimeMillis()));
} public static void main(String[] args) {
Worker worker = new Worker();
worker.handleWork(worker::doWork);
} @FunctionalInterface
private interface Handler<T, R> {
T handle(R r);
}
}

只要是符合返回值为String且参数为String的方法(例如:doWork方法)都可以作为Handler<String, String>类型的参数传入handleWork方法中进行执行