Related to this question
Given this function:
public static <S extends CharSequence> S foo(S s) {
return (S) new StringBuilder(s);
}
Why does this invocation execute without exception:
foo("hello");
But this one throws ClassCastException?
System.out.println(foo("hello"));
Generics in Java 5/6 are type-erased, which means that any generic type is fundamentally just an
Objecttype (or whatever the least common denominator type is, which is in this caseCharSequence) at runtime. The appropriate casts are inserted wherever needed. So your method gets type-erased to something that looks like this:And your call gets type-erased to this:
Apparently Java won’t bother inserting the
(String)cast if the return value is never used—why bother?