Ahmed Ashour Ahmed Ashour - 5 months ago 14
Java Question

MethodHandles.filterArguments() example gives an exception

With Java

1.8.0_92
, 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

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

Comments