Re: Dynamic Casting with Generics: Type Erasure Problems
On Mar 3, 2:42 pm, William <william.lichtenber...@gmail.com> wrote:
Here's what I don't like about the discussions here, and maybe because I'=
m not thinking about it clearly. Most errors thrown about type erasure a=
re legitimate, in that you can construct a scenario when it will not work. =
For instance... if I had the method
public <T extends Object> void testT(Class<T> type)
{
Class<T> testClass = Object.class;
}
That method will break if I called testT(String.class) because T is now S=
tring and Class<String> != Object.class. So that's a run time example =
of something that would break. In what scenario would my original exampl=
e not succeed?
Original example:
class WhyDoesntThis<T>
{
T instanceOfT;
T convertToT(Object object)
{
//compiler error: Type mismatch:
//cannot convert from capture#1-of ? extends Object to T
return instanceOfT.getClass().cast(object);
}
}
Because there's no way the compiler can know that "capture of ?" is
cast-compatible with T, it cannot prove that the cast is allowable.
The compiler only allows casts where one type is a supertype of the
other. "capture of ?" and "T" do not have that relationship.
It's not about scenarios, it's about the semantics of the cast
operator.
Take a look at the JLS for the details.
--
Lew