JDK 9 pre-review of JDK-6850612: Deprecate Class.newInstance since it violates the checked exception language contract

Joseph D. Darcy joe.darcy at oracle.com
Tue Apr 19 00:42:37 UTC 2016


With that feedback, I'll go ahead and prepare a changeset for the 
deprecation of this method and the suppression of the resulting warnings.



On 4/18/2016 5:26 PM, David Holmes wrote:
> I agree with Stuart.
> David
> On 19/04/2016 9:05 AM, Stuart Marks wrote:
>> On 4/17/16 10:31 AM, joe darcy wrote:
>>> With talk of deprecation in the air [1], I thought it would be a fine
>>> time to
>> "In the Spring a young man's fancy lightly turns to thoughts of
>> deprecation."
>>      -- apologies to Tennyson
>>> examine one of the bugs on my list
>>>      JDK-6850612: Deprecate Class.newInstance since it violates the
>>> checked
>>> 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,
>>> newInstanceWithProperExceptionBehavior,
>>> that had the same signature but wrapped exceptions thrown by the
>>> constructor
>>> 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().
>> s'marks

More information about the core-libs-dev mailing list