I'm learning reflection in Java and I write some 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 I run this code, I get:
java.lang.InstantiationException: Test$Base
at java.lang.Class.newInstance(Class.java:427)
at Test.main(Test.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.NoSuchMethodException: Test$Base.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 6 more
Could any one please tell me why? The constructor of the class base
is public
but the compiler still claims can't find its constructor..