Inner classes cannot exist outside the parent class. You need to construct the parent class first. Without reflection this would look like:
InnerClass innerClass = new TestClass().new InnerClass();
In reflection, you need to pass the parent class in during construction of the inner class.
Object testClass = Class.forName("com.example.TestClass").newInstance();
for (Class<?> cls : testClass.getClass().getDeclaredClasses()) {
// You would like to exclude static nested classes
// since they require another approach.
if (!Modifier.isStatic(cls.getModifiers())) {
Object innerClass = cls
.getDeclaredConstructor(new Class[] { testClass.getClass() })
.newInstance(new Object[] { testClass });
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…