Thursday, December 22, 2005

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:

Blogger Chris Nokleberg said...

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)

5:24 PM  
Blogger Bob Lee said...

Dammit, Chris. You win. At least I don't have to ship it. ;)

5:27 PM  
Blogger Chris Nokleberg said...

What can I say...one can never have too many t-shirts!

5:29 PM  

Post a Comment

Links to this post:

Create a Link

<< Home