关于反射调用内部类问题探索
/**
* @author: hellkity
* @date: Created in 2020/6/15
* 类说明: 非静态内部类 没有空构造器导致反射失败 的问题
* 非静态内部类 反射 调用会默认传一个参数 来动态创建实例
* 针对内部类
* 将内部类改为静态的可以解决问题
*/
public class Outer {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
new Outer().greetWorld();
}
private void greetWorld() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
System.out.println(Inner.class.newInstance());
//解决问题 1
//Constructor<Inner> c = Inner.class.getConstructor(Outer.class);
//System.out.println(c.newInstance(Outer.this));
}
//解决问题 2 将内部类改为静态
public /*static*/ class Inner {
public String toString(){
return "hello world";
}
}
}