在 Java 中,我可以将多个方法句柄与其参数组合起来,如下所示:
foo( a, bar( 2, b ) )
..通过使用 MethodHandles.collectArguments() .
我得到的方法句柄可以这样调用:
myHandle.invokeExact( 5, 6 ); // invokes foo(5, bar(2, 6))
但是现在,我想获得一个方法句柄,将其参数分派(dispatch)到调用树中,如下所示:
MethodHandle myHandle = ...; // foo( *x*, bar( 2, *x* ) )
myHandle.invokeExact( 3 ); // replaces x by 3 in both locations
// this call represents 'foo(3, bar(2, 3));'
我不知道该怎么做。你能帮我吗?
最佳答案
像往常一样,对 Java 方法句柄没有多大兴趣,所以我会给你答案:
使用MethodHandles::permuteArguments与 MethodType::dropPatameterTypes() 调用结合使用。
就我而言,只需这样做:
MethodHandle handle = [...]; // method handle representing f(x1, x2) = x1 + (x2 - 2)
MethodHandle h_permute = MethodHandles.permuteArguments(
handle,
handle.type().dropParameterTypes(1, 2), // new handle type with 1 less param
0,
0);
// h_permute now represents f(x) = x + (x - 2)
关于Java 方法句柄;在多个位置使用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37527774/