I am having trouble in accessing private method in private inner class that resides in different package than caller class:
package reflectiontest.sompackage;
import reflectiontest.Interface;
public class Outer {
private class Inner implements Interface {
public int get() {
return 4;
}
}
public Interface getInner() {
return new Inner();
}
}
package reflectiontest;
public interface Interface {
int get();
}
package reflectiontest;
import reflectiontest.sompackage.Outer;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
Outer outer = new Outer();
Interface inner = outer.getInner();
System.out.println(inner.get());
Method get = inner.getClass().getMethod("get");
System.out.println(get.invoke(inner));
}
}
Log after running:
4
Exception in thread "main" java.lang.IllegalAccessException: class reflectiontest.Main cannot access a member of class reflectiontest.sompackage.Outer$Inner with modifiers "public"
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:394)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:709)
at java.base/java.lang.reflect.Method.invoke(Method.java:569)
at reflectiontest.Main.main(Main.java:17)
During debugging i got to the point in Reflection.verifyMemberAccess()
fails at this point:
if (!Modifier.isPublic(getClassAccessFlags(memberClass))) {
isSameClassPackage = isSameClassPackage(currentClass, memberClass);
gotIsSameClassPackage = true;
if (!isSameClassPackage) {
return false;
}
}
The one option is to create a simple caller class inside the same package as Inner, but this seems a workaround.
Any other ideas on how to get it to work?
Aucun commentaire:
Enregistrer un commentaire