Use this:
public class MyReflection {
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
NoSuchMethodException, SecurityException, IllegalArgumentException,
InvocationTargetException {
Class outer = Class.forName("reflaction.MyReflection");
Object outerInstance = outer.newInstance();
Class<?> inner = Class
.forName("reflaction.MyReflection$TestReflection");
Constructor<?> constructor = inner.getDeclaredConstructor(outer);
TestReflection innerInstance = (TestReflection) constructor
.newInstance(outerInstance);
innerInstance.demo();
}
class TestReflection {
public void demo() {
System.out.println("reflection occurs");
}
}
Have a look at the Javadoc of getDeclaredConstructor(Class<?>... parameterTypes)
. It says:
... If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
So, giving the enclosing instance as first parameter will create a new instance of the inner class:
TestReflection innerInstance = (TestReflection) constructor
.newInstance(outerInstance);