Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8028129

Type checking: signature polymorphic MethodHandle.invoke(Object[])

XMLWordPrintable

    • b115
    • 8
    • generic
    • generic

      Let's consider following code:

      import java.lang.invoke.MethodHandle;
      import java.lang.invoke.MethodHandles;
      import java.lang.invoke.MethodType;
      import java.util.Arrays;

      interface MyFunctionalInterface {
          Object invokeMethodReference(Object... args) throws Throwable;
      }

      public class Test {
          public Object m(Object ... args) {
              System.out.println("m: " + Arrays.toString(args));
              return "m";
          }
          public static void main(String argv[]) throws Throwable {
              MethodHandles.Lookup lookup = MethodHandles.lookup();
              MethodType mt = MethodType.methodType(String.class, char.class, char.class);
              MethodHandle ms = lookup.findVirtual(String.class, "replace", mt);

              System.out.println("result: " + ms.invoke("some string to search", 's', 'o'));

              MyFunctionalInterface methodRefSimple = new Test()::m;

              methodRefSimple.invokeMethodReference("first", "second");
              MyFunctionalInterface methodRefSignPoly = ms::invoke;
              System.out.println(methodRefSignPoly.invokeMethodReference("some string to search", 's', 'o'));
          }
      }

      it causes following output:

      result: oome otring to oearch
      m: [first, second]
      Exception in thread "main" java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(String,char,char)String to (Object[])Object
      at java.lang.invoke.MethodHandle.asTypeUncached(MethodHandle.java:776)
      at java.lang.invoke.MethodHandle.asType(MethodHandle.java:770)
      at java.lang.invoke.Invokers.checkGenericType(Invokers.java:366)
      at Test$$Lambda$2/1761291320.invokeMethodReference(Unknown Source)
      at Test.main(Test.java:26)

      The following line:

      "System.out.println(methodRefSignPoly.invokeMethodReference("some string to search", 's', 'o'));"

      causes java.lang.invoke.WrongMethodTypeException to be thrown.

      JLS doesn't prohibit method references to signature polymorphic methods in any way. So I could believe it's a bug.

      The code above is attached for your convenience.

        1. Test.java
          1 kB
          Georgiy Rakov
        2. Test2.java
          0.9 kB
          Georgiy Rakov
        3. Test3.java
          0.9 kB
          Georgiy Rakov
        4. Test4.java
          0.7 kB
          Georgiy Rakov

            dlsmith Dan Smith
            grakov Georgiy Rakov (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: