Ahmed Ashour Ahmed Ashour - 1 year ago 60
Java Question

MethodHandles.filterArguments() example gives an exception

With Java

, on trying to run the example of MethodHandles.filterArguments(), the following exception is thrown:

Exception in thread "main" java.lang.invoke.WrongMethodTypeException: expected (String,String)String but found (String,String)Object
at java.lang.invoke.Invokers.newWrongMethodTypeException(Invokers.java:298)
at java.lang.invoke.Invokers.checkExactType(Invokers.java:309)
at SomeTest.main(SomeTest.java:15)

The code is:

import static java.lang.invoke.MethodHandles.filterArguments;
import static java.lang.invoke.MethodHandles.lookup;
import static java.lang.invoke.MethodType.methodType;

import java.lang.invoke.MethodHandle;

public class SomeTest {

public static void main(String[] args) throws Throwable {
MethodHandle cat = lookup().findVirtual(String.class,
"concat", methodType(String.class, String.class));
MethodHandle upcase = lookup().findVirtual(String.class,
"toUpperCase", methodType(String.class));
System.out.println(cat.invokeExact("x", "y"));
MethodHandle f0 = filterArguments(cat, 0, upcase);
System.out.println(f0.invokeExact("x", "y")); // Xy
MethodHandle f1 = filterArguments(cat, 1, upcase);
System.out.println(f1.invokeExact("x", "y")); // xY
MethodHandle f2 = filterArguments(cat, 0, upcase, upcase);
System.out.println(f2.invokeExact("x", "y")); // XY

Any idea what is wrong?

Answer Source

You can use invoke() instead of invokeExact() here, if you using invokeExact(), you should add cast to result type, like (String) invokeExact().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download