使用代码
TransferExecutor transferExecutor= new TransferExecutorImpl();
Function<Transfer, Void> commonLambda = transferExecutor::execute;
您正在将 绑定Function
到 的特定实例TransferExecutor
。您的动态创建代码缺少用于调用实例方法的实例TransferExecutorImpl.execute
。这就是异常试图告诉你的。
实例方法需要调用目标实例,因此您的目标方法的功能签名为(TransferExecutor,Transfer)→Void
.
您可以使用BiFunction<TransferExecutor,Transfer, Void>
此方法创建一个或将一个实例绑定到它,就像您的transferExecutor::execute
方法引用一样。对于后者
更改调用的类型以接收TransferExecutor
MethodType invokedType = MethodType.methodType(
Function.class, TransferExecutorImpl.class);
在调用时提供参数:
… .getTarget().invokeExact((TransferExecutorImpl)transferExecutor);
请注意,仍然存在细微差别。该语句Function<Transfer, Void> commonLambda = transferExecutor::execute;
引用接口方法,而您通过注释标识的方法是TransferExecutorImpl
.
关于绑定捕获的值,请参阅这个和那个答案以获得更多解释和示例。