JDK 8 code review request for 7140820 Add covariant overrides to Collections clone methods

Rémi Forax forax at univ-mlv.fr
Mon Jan 30 13:31:52 UTC 2012


On 01/30/2012 01:19 PM, Tom Hawtin wrote:
> On 30/01/2012 03:58, Joe Darcy wrote:
>
>> Object clone()
>>
>> method inherited from java.lang.Object with a covariant override such as
>>
>> MyType clone()
>
> This is, of course, going to break any existing overrides (that aren't 
> making use of covariant return types). This will be why the changes 
> weren't made way back in 1.5.
>
> Other clone implementations are overridden for (mobile code) security 
> reasons. These methods may have the same thing done to them by trusted 
> code outside of the Java library.
>
> A better solution to the unchecked casts from clone, is not to clone. 
> Using a constructor gets rid of the problem, and ensures you aren't 
> using some funky (potentially malicious) subclass.
>
> -            return (Hashtable<String, java.lang.Object>)_env.clone();
> +            return new Hashtable<>(_env);

don't forget that java.util.Property inherits from java.util.Hashtable.

Most of the time, the semantics wanted by the developer is the one of clone
and not the one of the copy constructor. You can safely use the copy 
constructor only
if the class is final.

>
> Tom

Rémi




More information about the core-libs-dev mailing list