Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heterogeneous container to store genericly typed objects in Java

Tags:

java

generics

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.

like image 424
Nick Cartwright Avatar asked May 26 '11 13:05

Nick Cartwright


1 Answers

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
like image 160
irreputable Avatar answered Sep 29 '22 23:09

irreputable