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

Bad NullPointerException message when invoking an interface MethodHandle on a null receiver

XMLWordPrintable

    • b16
    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      When the JVM invokes `DirectMethodHandle.checkReceiver(…)` and the receiver is null, the resulting `NullPointerException` message is unhelpful.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run the attached Java program.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The message of the thrown `NullPointerException` should have a better error message.
      ACTUAL -
      The `NullPointerException` has the message:
      ```
      Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "recv" is null
              at java.base/java.lang.invoke.DirectMethodHandle$Interface.checkReceiver(DirectMethodHandle.java:476)
              at Test.main(Test.java:17)
      ```

      ---------- BEGIN SOURCE ----------
      import java.lang.invoke.*;
      import java.util.Iterator;

      import static java.lang.invoke.MethodHandles.*;
      import static java.lang.invoke.MethodType.*;

      class Test {
      public static void main(final String... args) throws Throwable {
      final var lookup = lookup();
      final var mh = lookup.findVirtual(Iterable.class, "iterator", methodType(Iterator.class));

      __ignore((Iterator<?>) mh.invokeExact((Iterable<?>) null));
      }

      private static <T> void __ignore(T arg) {}
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Adding a custom null‑check with a better error message before the `MethodHandle.invoke(Exact)` call.

      FREQUENCY : always


            mchung Mandy Chung (Inactive)
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: