In my example I have two packages: package1
contains class A
(NOT declared as public) and its nested static class B
(declared as public):
package package1;
class A {
public static class B {
public B() {
}
}
public A() {
}
}
package2
contains a Main
class with a simple main method that tries to reflectively create an instance of class package1.A$B
:
package package2;
public class Main {
public static void main(String[] args) {
try {
Class<?> innerClass = Class.forName("package1.A$B");
Object o = innerClass.newInstance();
System.out.println(o);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
}
Surprisingly (at least for me), this piece of code succeeds in doing something otherwise impossible without reflection. Classic import
statements (like import package1.A.B;
or import package1.A.*;
) raise errors arguing that class A
is not visible. Moreover, there is no need to require special accessibility priviledges to create the instance of B
. Is it a normal behaviour?
EDIT: It works also if I get a reference to the inner class in a different way, like this:
Class<?> innerClass = Class.forName("package1.A").getClasses()[0];