【发布时间】:2020-05-02 18:10:14
【问题描述】:
import java.lang.reflect.*;
public class Test {
public Test(int x) {
System.out.println("Constuctor called! x = " + x);
}
public static void main(String[] args) throws Exception {
Class<? extends Thing> clazz = Stuff.class;
Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
Thing instance = ctor.newInstance(5);
}
}
public class Thing{
public Thing(int x){
System.out.println("Constructor! x = " + x);
}
}
public class Stuff extends Thing{
public Stuff(int x){
super(x*2);
}
}
上面的代码按预期工作。
import java.lang.reflect.*;
public class Test {
public Test(int x) {
System.out.println("Constuctor called! x = " + x);
}
static void Create(){
Class<? extends Thing> clazz = Stuff.class;
Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
Thing instance = ctor.newInstance(5);
}
public static void main(String[] args) throws Exception {
Create();
}
}
public class Thing{
public Thing(int x){
System.out.println("Constructor! x = " + x);
}
}
public class Stuff extends Thing{
public Stuff(int x){
super(x*2);
}
}
此代码没有。我收到这些错误:
/tmp/java_tXpJ5P/Test.java:11: error: unreported exception NoSuchMethodException; must be caught or declared to be thrown
Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
^
/tmp/java_tXpJ5P/Test.java:12: error: unreported exception InstantiationException; must be caught or declared to be thrown
Thing instance = ctor.newInstance(5);
^
2 errors
我在这里遗漏了一些非常明显或非常神秘的东西吗?这似乎很奇怪。 这是一个更复杂的项目中代码的简化,其结构略有不同(我将 Class 作为参数传递)但产生相同的错误。
非常感谢
【问题讨论】:
-
好吧,异常消息只是告诉它——
newInstance()声明它可能抛出一个NoSuchMethodException。这是一个已检查异常,因此调用它的方法应该使用 try/catch 处理它或声明它被抛出。在您的第一个代码 sn-p 中,main声明了一个可能的Exception被抛出,以满足编译器的要求。但是,您的Create方法应该没有 throws 子句。Create()应该是create() throws NoSuchMethodException, InstantiationException。
标签: java