Reflection cannot access default method of non-public interface

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      If a public class implements a non-public interface that declares a default public method, this method cannot be accessed through reflection, within the public class. Attempting to access the default public method from outside the package will produce a java.lang.IllegalAccessException.
      An analogous case has been reported in JDK-6342411, and to make the behaviour consistent with this case, I suggest that some kind of bridge method is added to the class file of the public class, such that the method can be accessed through reflection (as it is a public method within a public class).

      Sidenote: calling the public method directly from the public class (in this case and in JDK-6342411) is fine and does not throw an exception.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Simply compiling the given code and executing the main method in ClientTest should produce the same behaviour.
      If instead, in the ClientTest code, we simply use im.f(), we get the expected result.

      ACTUAL -
      Exception in thread "main" java.lang.IllegalAccessException: class foo.client.ClientTest cannot access a member of interface foo.DefaultInterface with modifiers "public"
              at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:400)
              at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:670)
              at java.base/java.lang.reflect.Method.invoke(Method.java:556)
              at foo.client.ClientTest.main(ClientTest.java:11)


      ---------- BEGIN SOURCE ----------
      package foo;

      interface DefaultInterface {

      default public void f() {
      System.out.println("Hi");
      }
      }
      ----------------------------------
      package foo;

      public class Impl implements DefaultInterface{

      }
      ----------------------------------
      package foo.client;

      import java.lang.reflect.Method;

      import foo.Impl;

      public class ClientTest {
          public static void main(String[] args) throws Exception {
           Impl im = new Impl();
           Method m = Impl.class.getMethod("f");
           m.invoke(im);
          }
      }
      ---------- END SOURCE ----------

        1. ClientTest.java
          0.2 kB
          Patricia Tavares
        2. DefaultInterface.java
          0.1 kB
          Patricia Tavares
        3. Impl.java
          0.1 kB
          Patricia Tavares

            Assignee:
            Unassigned
            Reporter:
            Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: