4

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.

Zeemee
  • 10,486
  • 14
  • 51
  • 81

1 Answers1

7

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    Wouldn't the `IOException` be wrapped in the `InstantiationException`? – Paul Bellora Sep 03 '13 at 15:23
  • InstantiationException is when `the class object represents an abstract class, an interface, an array class, a primitive type, or void OR the class has no nullary constructor` There is an `ExecutionException` for this when calling `Constructor.newInstance()` – Peter Lawrey Sep 03 '13 at 15:24
  • Interesting, I always though it functioned like `InvocationTargetException`. That's definitely a gotcha. – Paul Bellora Sep 03 '13 at 15:28
  • @PaulBellora One of four ways to throw a CheckedException without the compiler knowing (without JNI) :P – Peter Lawrey Sep 03 '13 at 15:34
  • 1
    I'll have to update [an answer of mine](http://stackoverflow.com/a/11943139/697449) about that, thanks for teaching me something. – Paul Bellora Sep 03 '13 at 15:39
  • @PaulBellora A puzzle for you, can you guess another three ;) – Peter Lawrey Sep 03 '13 at 15:40