1

In Java, I am able to combine multiple method handle with each its parameters, like this:

foo( a, bar( 2, b ) )

..by using MethodHandles.collectArguments().

The method handle I get can be called like this :

myHandle.invokeExact( 5, 6 ); // invokes foo(5, bar(2, 6))

But now, I would like to get a Method Handle that dispatches its parameters into the call tree like this:

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));'

I cannot wrap my head around about how to do that. Can you help me?

Gui13
  • 12,993
  • 17
  • 57
  • 104

1 Answers1

2

As usual for Java Method Handles, not much interest, so I will give you the answer:

Use MethodHandles::permuteArguments combined with a MethodType::dropPatameterTypes() call.

In my case, it is simply a matter of doing this:

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)
Gui13
  • 12,993
  • 17
  • 57
  • 104
  • I wouldn’t say that there is “not much interest”, but the `methodhandle` tag, having 41 questions, is quite narrow. Adding a [tag:reflection] or [tag:bytecode], while not matching the matter exactly, could raise the attention. – Holger Jun 02 '16 at 08:54