JDK 9 pre-review of JDK-6850612: Deprecate Class.newInstance since it violates the checked exception language contract
peter.levart at gmail.com
Tue Apr 19 10:41:00 UTC 2016
On 04/19/2016 01:05 AM, Stuart Marks wrote:
> On 4/17/16 10:31 AM, joe darcy wrote:
>> With talk of deprecation in the air , I thought it would be a fine
>> time to
> "In the Spring a young man's fancy lightly turns to thoughts of
> -- apologies to Tennyson
>> examine one of the bugs on my list
>> JDK-6850612: Deprecate Class.newInstance since it violates the
>> exception language contract
>> As the title of the bug implies, The Class.newInstance method
>> knowingly violates
>> the checking exception contract. This has long been documented in its
>> specification: [...]
>> Comments on the bug have suggested that besides deprecating the
>> method, a new
>> method on Class could be introduced,
>> that had the same signature but wrapped exceptions thrown by the
>> call in the same way Constructor.newInstance does.
> Deprecating Class.newInstance() seems reasonable to me, for the
> reasons you've stated.
> It's not clear to me that a replacement method adds much value. I
> believe it's possible to replace a call
> clazz.newInstance() // 1
> with the call
> clazz.getConstructor().newInstance() // 2
> which is only a bit longer. Both snippets are declared to throw
> InstantiationException and IllegalAccessException. But snippet 2 also
> is declared to throw InvocationTargetException and NoSuchMethodException.
> This would seem to be an inconvenience, but *all* of these exceptions
> are subtypes of ReflectiveOperationException. It seems pretty likely
> to me that most code handles these different exception types the same
> way. So it's fairly low cost to replace snippet 1 with snippet 2, and
> to adjust the exception handling to deal with
> ReflectiveOperationException. Thus I don't see much value in adding a
> new method such as Class.newInstanceWithProperExceptionBehavior().
...except for performance. The Class.newInstance() does special
constructor and caller caching so that access checks don't have to be
performed at every invocation.
Performance sensitive user code using Class.newInstance() should then
probably be modified to obtain Constructor only once and then re-use it
for multiple invocations.
More information about the core-libs-dev