为什么newInstance()返回null? [英] Why does newInstance() return null?

查看:178
本文介绍了为什么newInstance()返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 JavaDocs java.lang.ClassnewInstance()方法无意返回null. 但是我的代码似乎证明是相反的.为什么?

According to the JavaDocs, the newInstance() Method of java.lang.Class is not intented to return null. But my code seems to prove the opposite. Why?

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;
}

它返回null.

推荐答案

newInstance()从不返回null.但是newInstance().toString()可以返回"null"

newInstance() never returns null. However newInstance().toString() can return "null"

注意:使用newInstance()的一个陷阱是它可以抛出CheckedException!

Note: One gotcha with newInstance() is that it can throw a 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()会抛出此检查异常.如果您试图抓住它,编译器会抱怨它不能被抛出!

Even though IOException is a check exception, the compiler has not idea the newInstance() will throw this checked exception. If you try to catch it the compiler will complain it cannot be thrown !!

这篇关于为什么newInstance()返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆