Why does newInstance() return null?

2019-05-09 07:36发布

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

It returns null.

1条回答
成全新的幸福
2楼-- · 2019-05-09 08:22

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

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

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 !!

查看更多
登录 后发表回答