Why is Class.newInstance () deprecated in Java 9?

Why is Class.newInstance () deprecated in Java 9?

I read Javadoc 9:

Outdated. This method extends to any exception thrown by the constructor with a null value, including the checked exception. Using this method effectively bypasses the compilation time exception check, which otherwise would have been executed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) InvocationTargetException.

but I'm not sure that I understood it ...

"Raises any exception thrown by a constructor with a zero number" - wouldn't it be right? Perhaps there are many points that I miss.

Change A question identified as duplicate answers, citing Javadoc, asks a question about Javadoc.

+7
java reflection deprecated java-9
source share
2 answers

The fact is that newInstance() does not throw any exceptions, although the null constructor of the class in question can raise checked exceptions.

+9
source share

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){ // handling the exception thrown by the constructor } 

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.

+8
source share

All Articles