package com.net.test;
public class Outer {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@SuppressWarnings("unused")
private class Inner {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private String invoke() {
return "Hello, Inner Class";
}
}
}
package com.net.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestInner {
/**
* @param args
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException,
SecurityException, ClassNotFoundException {
Outer outerObject = new Outer();
// Class<?> innerClass = Outer.class.getDeclaredClasses()[0];
Class<?> innerClass = Class.forName("com.net.test.Outer$Inner");
Constructor<?> constructor = innerClass.getDeclaredConstructors()[0];
constructor.setAccessible(true);
Object innerObject = constructor.newInstance(outerObject);
Method innerMethod = innerObject.getClass().getDeclaredMethod("invoke");
innerMethod.setAccessible(true);
String str = (String) innerMethod.invoke(innerObject);
System.out.println(str);
}
}