0

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?

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
  • 1
    Some informations from doc about invokeExact:Invokes the method handle, allowing any caller type descriptor, but requiring an exact type match. * The symbolic type descriptor at the call site of {@code invokeExact} must * exactly match this method handle's {@link #type type}. * No conversions are allowed on arguments or return values. – star Jun 08 '16 at 07:44

1 Answers1

1

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

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
achist
  • 51
  • 3