It is deprecated in Java 9, but note that Class.newInstance() has not been discussed before.
The alternative to Constructor.newInstance() not a new thing .
The Class.newInstance() method Class.newInstance() checked exceptions that should be handled by design.
Here is the declaration of Class.newInstance() :
public T newInstance() throws InstantiationException, IllegalAccessException
Constructor.newInstance() provides a way to handle these checked exceptions from the client side by throwing an InvocationTargetException :
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException)
InvocationTargetException is a checked exception. It must be processed.
And it provides a method to get the exception thrown by the constructor: getTargetException() .
Suppose a constructor class Foo throws a validation exception:
public class Foo{ public Foo() throws IOException { } }
Using Constructor.newInstance() , clients using reflection are now forced to handle InvocationTargetException , which can be thrown and wrapped in an exception (Runtime or checked).
For example:
Constructor<Foo> constructor = ...; try{ Foo foo = constructor.newInstance(); } catch (InvocationTargetException e){
With Class.newInstance() clients can forget / not handle an IOException , because Class.newInstance() does not throw a checked exception to handle:
Class<Foo> clazz = Foo.class; Foo foo = clazz.newInstance();
As a result, an IOException, which is a checked exception, will be thrown, and the code that throws it will never explain.
davidxxx
source share