【问题标题】:Why does newInstance() return null?为什么 newInstance() 返回 null?
【发布时间】:2013-09-03 14:26:23
【问题描述】:

根据JavaDocsjava.lang.ClassnewInstance() 方法无意返回null。 但我的代码似乎证明了相反的情况。为什么?

public Assessment createAssessment() {
    Class<? extends Assessment> assessmentClass = (Class<? extends Assessment>) assessmentClassDataTable.getRowData();
    try {
        System.out.println("ASSESSMENTCLASS " + assessmentClass);
        // -> 'ASSESSMENTCLASS class my.model.ManualSelectAssessment'
        Assessment a = assessmentClass.newInstance();
        System.out.println("ASSESSMENT " + a);
        // -> 'ASSESSMENT null'
        return a;
    } catch (Exception e) {
        Application.handleError(e);
    }
    return null;
}

它返回空值。

【问题讨论】:

  • ManualSelectAssessmenttoString方法能否返回"null"
  • 想必你确定它没有抛出异常,被捕获然后返回null?
  • 确保你的类有一个无参数构造函数
  • 您正在打印a.toString() 的结果,而不是“返回”null。看看有没有a == null
  • 当您使用默认构造函数进行实例化时,您的 tostring 方法中有些东西没有价值。

标签: java generics reflection


【解决方案1】:

newInstance() 永远不会返回 null。但是newInstance().toString() 可以返回"null"

注意:newInstance() 的一个问题是它可以抛出 CheckedException!

public Main() throws IOException {
    throw new IOException();
}

public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    Main.class.newInstance(); // throws IOException silently.
}

即使 IOException 是一个检查异常,编译器也不知道 newInstance() 会抛出这个检查异常。如果你试图捕捉它,编译器会抱怨它不能被抛出!

【讨论】:

  • IOException 不会被包裹在 InstantiationException 中吗?
  • InstantiationException 是当the class object represents an abstract class, an interface, an array class, a primitive type, or void OR the class has no nullary constructor 调用Constructor.newInstance() 时有一个ExecutionException 用于此
  • 有趣,我一直认为它的功能类似于InvocationTargetException。这绝对是一个陷阱。
  • @PaulBellora 在编译器不知道(没有 JNI)的情况下抛出 CheckedException 的四种方法之一:P
  • 我必须更新an answer of mine,谢谢你教我一些东西。
猜你喜欢
  • 2022-12-26
  • 2016-12-28
  • 2015-11-25
  • 2015-07-04
  • 2019-09-29
  • 2015-02-25
  • 2015-10-21
  • 2021-08-12
  • 2011-03-18
相关资源
最近更新 更多