Avoiding Returning Wildcard Types

后端 未结 4 1565
暗喜
暗喜 2021-02-08 10:26

I have a class with a collection of Wildcard Types that is a singleton, something like:

public ObliviousClass{

    private static final ObliviousClass INSTANCE          


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 10:58

    Here's a type-safe way to store multiple instances of a given type in a map. The key is that you need to provide a Class instance when retrieving values in order to perform runtime type-checking, because static type information has been erased.

    class ObliviousClass {
    
      private final Map map = new HashMap();
    
      public Object put(Key key, Object value)
      {
        return map.put(key, value);
      }
    
      public  T get(Key key, Class type)
      {
        return type.cast(map.get(key)); 
      }
    
    }
    

    Usage would look like this:

    oc.put(k1, 42);
    oc.put(k2, "Hello!");
    ...
    Integer i = oc.get(k1, Integer.class);
    String s = oc.get(k2, String.class);
    Integer x = oc.get(k2, Integer.class); /* Throws ClassCastException */
    

提交回复
热议问题