【问题标题】:Java: getConstructor + newInstance working in main but not outside it - exactly the same code [duplicate]Java:getConstructor + newInstance 在 main 中工作但不在它之外 - 完全相同的代码 [重复]
【发布时间】: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


【解决方案1】:

你的主要方法throws Exception,这意味着无论那里发生什么都会被抛出。 您的新代码没有 throws Exception 并且您的代码正在抛出 2 个潜在异常(InstantiationExceptionNoSuchMethodException)。您必须照顾它们,要么抛出(作为主要方法),要么将其包装在 try-catch 语句中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2014-07-28
    相关资源
    最近更新 更多