Java Reference
In-Depth Information
which has the unfortunate consequence that use of this method always
results in an "unchecked" warning by the compiler. A generic version
might be specified as
public static <T> T[] newInstance(Class<T> type, int length)
but not only is that not backward compatible, it precludes creating ar-
rays where the component type is a primitive type. So even with a type-
safe generic method, you'd still need a second method to allow primitive
array creation.
There is a similar problem with implementing the clone method: You
cannot define a clone method for a parameterized type without getting
an "unchecked" warning when you cast the Object result of Object.clone
to the correct type. This is one of those rare occasions in which a cast
using the expected parameterized type is the right thing to do. For ex-
ample, given a generic class Cell<E> , the clone method should be de-
clared to return an instance of Cell<E> because that will permit the caller
of clone to use the returned object without the need for any casts. To
declare clone in that way requires that the result of super.clone be cast
to Cell<E> , which incurs the "unchecked" warning. But be warned, an er-
roneous or malicious clone implementation could still return an object of
the wrong type.
As you generify you own applications and libraries you must be aware
of these issues in order to maintain the right level of compatibility with
users of your code.
Things will get better despite our efforts to improve them.
Will Rogers
 
Search WWH ::




Custom Search