I don't know why no one provided a simple example based explanation to this, as compared to Constructor::newInstance
for example, since finally Class::newInstance
was deprecated since java-9.
Suppose you have this very simple class (does not matter that it is broken):
static class Foo {
public Foo() throws IOException {
throw new IOException();
}
}
And you try to create an instance of it via reflection. First Class::newInstance
:
Class<Foo> clazz = ...
try {
clazz.newInstance();
} catch (InstantiationException e) {
// handle 1
} catch (IllegalAccessException e) {
// handle 2
}
Calling this will result in a IOException
being thrown - problem is that your code does not handle it, neither handle 1
nor handle 2
will catch it.
In contrast when doing it via a Constructor
:
Constructor<Foo> constructor = null;
try {
constructor = clazz.getConstructor();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
Foo foo = constructor.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
System.out.println("handle 3 called");
e.printStackTrace();
}
that handle 3 will be called, thus you will handle it.
Effectively, Class::newInstance
bypasses the exception handling - which you really don't want.