Avoiding Returning Wildcard Types

后端 未结 4 1567
暗喜
暗喜 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:50

    Your ObliviousClass, by design, doesn't know the parameterized type of the item it holds. So to be type safe, you should avoid such design :-\

    But if you want to keep it, first things is that you will have to cast. There is no way out of this. But the way you do it is very error prone. For example:

    oc.put(k1, intType);
    oc.put(k2, strType);
    Type<Integer> tint = oc.get(k1, Integer.class)
    Type<String>  tstr = oc.get(k1, String.class)  // typo in k2: compile fine
    

    And worst, due to type erasure, it will fail at runtime only once you actually use tstr, not when you get it from ObliviousClass.

    So you can improve safety by tracking the parameterized type in some other way. For example, you could associate the key to the type, not losing it:

    @Value // lombok
    class Key<T> {
        private int index;
    }
    
    class Type<T> {}
    
    class ObliviousClass {
    
        // side note: static final can be public safely
        public static final ObliviousClass instance = new ObliviousClass();
    
        private List<Type<?>> map = new ArrayList<>();
    
        public <T> Key<T> appendType(Type<T> type){
            // here, I found it nicer that obliviousClass generates and return the key
            // otherwise use:  "public <T> void appendType(key<T> key, Type<T> type)"
            // that binds parametrized type of both key and type arguments
            map.add(type);
            return new Key<>(map.size() - 1);
        }
    
    
        public <T> Type<T> get(Key<T> key){
            return (Type<T>) map.get(key.index);
        }
    }
    

    Then you can use it such as:

        Type<Integer> intType = new Type<>();
        Type<String>  strType = new Type<>();
        Key<Integer> k1 = ObliviousClass.instance.appendType(intType);
        Key<String>  k2 = ObliviousClass.instance.appendType(strType);
    
        Type<Integer> t1 = ObliviousClass.instance.get(k1);
        Type<String>  t2 = ObliviousClass.instance.get(k2);
        Type<String>  t3 = ObliviousClass.instance.get(k1); // won't compile
    
    0 讨论(0)
  • 2021-02-08 10:51

    For those landing on this question these many years later, this is not how Java generics are designed to be used. (I was going to comment but had more to details.)

    The generic pattern manages a single parent class per type ID rather than multiple different classes. If we consider the simpler List<T>, a list of strings OR integers (as List<String> or List<Integer>) is how generics are defined. One class per type. This way, there is a consistent type when the values are referenced. Storing unrelated types would be the same as List<Object>. Only the programmer can know when multiple types are stored and how to retrieve them with casting.

    It would be ok to store subclasses to a parent class, but when accessed from the collection without casting, the parent class contact is all that is known. For instance, a generic collection defined with an interface like Map<String, Runnable>. However, only the run() method is visible even if other public methods are added to implementations (unless the programmer explicitly casts). To access additional methods, casting is necessary.

    This is a limitation in Java. A language could be defined to know the L-Value type - even Java. But it wasn't. When new features are added, there are many backward compatible considerations [Sun and] Oracle take into account. Code compiled with generics was designed to run on older JVMs with type erasure. Java uses type erasure at compile time once it has determined that the generics are consistently reference. The bytecode uses Object as if the instance was (sort of) defined as List. If the choice was made to abandon backward compatibility, like Java 9 and 11, then multiple types might have been workable.

    0 讨论(0)
  • 2021-02-08 10:57

    Simply type your class:

    public ObliviousClass <T> {
    
        private Map<Key, Type<T>> map = new HashMap<Key, Type<T>>();
    
        public void putType(Key key, Type<T> type){
            map.put(type);
        }
    
        public Type<T> getType(Key key){
            map.get(key);
        }
    }
    

    FYI, at this point you have the delegation pattern in play.

    Your example client code would need to declare two instances of ObliviousClass: ObliviousClass<String> and ObliviousClass<Integer>.

    Edit:

    If you must have a mixed bag of Types, you can impose a type on your method, but you'll get a compiler warning for an unsafe cast:

    public class ObliviousClass {
    
        private final Map<Key, Type<?>> map = new HashMap<Key, Type<?>>();
    
        public void putType(Key key, Type<?> value) {
           map.put(key, value);
        }
    
        @SuppressWarnings("unchecked")
        public <T> Type<T> getType1(Key key, Class<T> typeClass) {
           return (Type<T>)map.get(key); 
        }
    
        @SuppressWarnings("unchecked")
        public <T> Type<T> getType2(Key key) {
            return (Type<T>) map.get(key);
        }
    }
    

    Clients can type the calls to these methods like this:

    Type<Integer> x = obliviousClass.getType1(key, Integer.class);
    Type<Integer> y = obliviousClass.<Integer>getType2(key);
    

    Take your pick as to which one you prefer and use that.

    0 讨论(0)
  • 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<Key, Object> map = new HashMap<Key, Object>();
    
      public Object put(Key key, Object value)
      {
        return map.put(key, value);
      }
    
      public <T> T get(Key key, Class<? extends T> 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 */
    
    0 讨论(0)
提交回复
热议问题