您好,我想使用反射获取内部类的对象,但我在其中遇到了一些错误。
代码是:-
package reflaction;
public class MyReflection {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class obj = Class.forName("reflaction.MyReflection$TestReflection");
TestReflection a = (TestReflection) obj.newInstance();
a.demo();
}
class TestReflection {
public void demo(){
System.out.println("reflection occurs");
}
}
}
错误是:--
Exception in thread "main" java.lang.InstantiationException: reflaction.MyReflection$TestReflection
at java.lang.Class.newInstance0(Class.java:357)
at java.lang.Class.newInstance(Class.java:325)
at reflaction.MyReflection.main(MyReflection.java:10)
用这个:
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");
}
}
看看Javadoc of getDeclaredConstructor(Class<?>... parameterTypes)
。它说:
...如果此 Class 对象表示在非静态上下文中声明的内部类,则形式参数类型包括显式封闭实例作为第一个参数。
因此,将封闭实例作为第一个参数将创建内部类的新实例:
TestReflection innerInstance = (TestReflection) constructor
.newInstance(outerInstance);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)