reflection - Why I get java.lang.InstantiationException here? -
this question has answer here:
i'm learning reflection in java , write test code:
import java.lang.reflect.invocationtargetexception; import java.lang.reflect.method; public class test { class base { public base() {} public void print(){ system.out.println("base"); } } class derived extends base { @override public void print() { system.out.println("derived"); } } public static void main(string args[]) { try { class.forname(derived.class .gettypename()) .getsuperclass() .getmethod("print", new class[0]) .invoke(base.class.newinstance());// line 41 } catch (classnotfoundexception e) { e.printstacktrace(); } catch (nosuchmethodexception e) { e.printstacktrace(); } catch (invocationtargetexception e) { e.printstacktrace(); } catch (illegalaccessexception e) { e.printstacktrace(); } catch (instantiationexception e) { e.printstacktrace(); } } }
but when run code, get:
java.lang.instantiationexception: test$base @ java.lang.class.newinstance(class.java:427) @ test.main(test.java:41) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:497) @ com.intellij.rt.execution.application.appmain.main(appmain.java:140) caused by: java.lang.nosuchmethodexception: test$base.<init>() @ java.lang.class.getconstructor0(class.java:3082) @ java.lang.class.newinstance(class.java:412) ... 6 more
could 1 please tell me why? constructor of class base
public
compiler still claims can't find constructor..
because base
inner class , all (*) inner class constructors implicitly declare formal parameter of enclosing class @ index 0.
the constructor of (*) non-private inner member class implicitly declares, first formal parameter, variable representing enclosing instance of class (§15.9.2, §15.9.3).
in other words, it's not parameterless constructor. you'll need use class#getconstructor(class[])
appropriate constructor, invoke it.
base instance = base.class.getconstructor(test.class).newinstance(new test()); class.forname(derived.class.gettypename()).getsuperclass().getmethod("print", new class[0]).invoke(instance);
(all inner classes hard work with.)
Comments
Post a Comment