15

I am trying to follow Joshua Bloch's typesafe hetereogeneous container pattern from Effective Java to create a container of objects (MyGeneric<T>) with Class<T> as a key.

  public class MyClass {

    private Map<Class<?>, MyGeneric<?>> myContainer =
      new HashMap<Class<?>, MyGeneric<?>>();

    public <T> void addToContainer(Class<T> class, MyGeneric<T> thing) {
      myContainer.put(class, thing);
    }

    public <T> MyGeneric<T> getFromContainer(Class<T> class) {
      return (MyGeneric<T>)(myContainer.get(klass));
    }
  }

The problem is in getFromContainer I have to perform a unchecked cast. In Josh Bloch's container, he performs a safe cast - but in my case I can't see a way how this is possible.

Does any one have any ideas?

Cheers, Nick.

aioobe
  • 413,195
  • 112
  • 811
  • 826
Nick Cartwright
  • 8,334
  • 15
  • 45
  • 56

1 Answers1

10

In Bloch's version, Class.cast() is used - which is implemented as return (T) obj, an unchecked cast. It's cheating in the sense that the compiler warning about unchecked cast is moved to a precompiled lib. The type safety of the cast is not guarded by compiler, but by app logic.

You shouldn't worry about unchecked cast either. There are type relations that cannot be expressed in the language, but which programmers know to be true. So just overrule the compiler, tell it the cast is safe.

Correction

My understanding about "unchecked cast" was incorrect.

Class.cast() does not contain "unchecked cast". The cast is done after "checking", if the cast is reached at runtime, it's guaranteed to succeed.

T cast(Object obj)
    if obj is instance of this class   // check
        return (T)obj;                 // cast 
    else
        throw new ClassCastException
irreputable
  • 44,725
  • 9
  • 65
  • 93
  • Thank you. Is it best practice to suppress the 'unchecked' warning this generates, or leave it in as with a comment to highlight to any one else who may in the future want to update the class? – Nick Cartwright May 26 '11 at 13:59
  • OK - for those interested, I suppressed the warning & added a comment! N – Nick Cartwright May 26 '11 at 16:12