在运行这个程序之后,我得到了java.lang.InstantiationException,但是我期望一个Hello 作为输出。
public class Test {
public static void main(String[] args) throws Exception {
new Test().greetWorld();
}
private void greetWorld() throws Exception {
System.out.println(Test2.class.newInstance());
}
class Test2 {
public String toString() {
return "Hello world";
}
}
}有人能告诉我这个例外吗?为什么它不打印Hello ?
发布于 2017-04-26 06:13:45
这是因为Test2不是static类。让它static来使这个工作。
static class Test2 {
public String toString() {
return "Hello world";
}
}或者,将Test2移出Test1。
考虑一下通常如何创建Test2的实例。因为它不是静态的,所以你不能就这样
Test1.Test2 obj = new Test1.Test2();您需要处于Test1的非静态上下文中。
这就是为什么不能直接从Class对象获取构造函数的原因。
https://stackoverflow.com/questions/43626178
复制相似问题