Generics Puzzler
Does the following code compile?
class Puzzler { <T> T cast(T t, Class<T> clazz) { return clazz.cast(t); } <T> T nop(T t) { return cast(t, t.getClass()); } }Why not? Update: To make things more interesting, in Mary's honor, I'll ship a free Google t-shirt (paid for out of my pocket) to the first person to post a comment with the correct answer (judged by me).
3 Comments:
Hi Bob :-) No it does not compile, because Object#getClass is declared to return Class[? extends Object] instead of Class[T]. This is because the result type of getClass is the "erasure of the static type" of the argument. For example, if you call getClass on a Number, you will actually get back Class[Integer], not Class[Number], so the best the compiler can allow is Class[? extends Number]. (Blogger doesn't like generic angle brackets very much)
Dammit, Chris. You win. At least I don't have to ship it. ;)
What can I say...one can never have too many t-shirts!
Post a Comment
<< Home