The problem is that your testing method does not really call NestedClass.foo() . This line:
NestedClass.foo();
... actually converts to a synthetic method call that is generated in foo , for example:
NestedClass.access$000();
Where access$000 as follows:
// Note package access static void access$000() { foo(); }
You can verify this using javap -c to view the actual bytecode.
At the JVM level, your outer class does not have access to foo() . The Java compiler simply synthesizes access to it, creating access$000 and calling it from your outer class whenever the source code calls foo() .
At runtime, reflection libraries do not do the same, so your mistake.
source share