Can't call certain accessible methods using reflection

Peter Levart peter.levart at gmail.com
Mon Nov 28 11:23:10 UTC 2016


Hi,

I encountered a situation in which calling a method using reflection is 
not possible, while the same method can be called with bytecode instruction.

Here's an example:

// Module m1:

module m1 {
     exports pkg1;
}

package internal;
public class InternalImpl {
     public void m() {
         System.out.println("m()");
     }
}

package pkg1;
public class Public extends internal.InternalImpl {
}


// Module m2:

module m2 {
     requires m1;
}

package pkg2;
import pkg1.Public;
import java.lang.reflect.Method;
public class Main {
     public static void main(String[] args) throws Exception
         Public p = new Public();
         // using bytecode
         p.m();
         // using reflection
         Method m = Public.class.getMethod("m");
         m.invoke(p);
         // IllegalAccessException: class pkg2.Main (in module m2) 
cannot access class internal.InternalImpl (in module m1) because module 
m1 does not export internal to module m2
     }
}


Similar situation would arise if Public class extended a package-private 
class containing public method m(). But in this case javac helps 
reflection by creating a bridge method in Public class which just 
delegates to super. I don't know if it would be wise to expect the same 
from javac for subclasses of public classes in non-exported packages or 
packages that are exported to just certain modules?

Regards, Peter



More information about the jigsaw-dev mailing list