Re: Dynamic Casting with Generics: Type Erasure Problems
On Mar 3, 11:34 am, markspace <-@.> wrote:
On 3/3/2011 8:12 AM, William wrote:
In both cases, the instance can be a subclass of the class that is
defined, but that should be okay, because it only has to honor the
parent's interface.
Yeah, getClass() returns Class<?>, not Class<T>. So they don't match.
Read the docs on methods you don't think are "working."
Fyi, this does work:
class WhyDoesntThis<T>
{
T instanceOfT;
T convertToT(Object object)
{
// just cast
return (T) object;
}
}
Don't you need to '@SuppressWarnings()' and catch the
'ClassCastException'?
Not that you need to-need to, but it's bad practice not to, therefore
you need to.
The tricky thing with wildcards, and Brian Goetz has some excellent
articles about this on DeveloperWorks/java, is that they guarantee a
capture, just not which capture.
So if "? extends T" and you only know "T", you cannot be sure that the
"T" you have will correctly downcast to the capture of the "?". Hence
the error.
"? extends" prevents puts, "? super" prevents gets.
--
Lew