Avoiding Returning Wildcard Types

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

    Simply type your class:

    public ObliviousClass  {
    
        private Map> map = new HashMap>();
    
        public void putType(Key key, Type type){
            map.put(type);
        }
    
        public Type 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 and ObliviousClass.

    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> map = new HashMap>();
    
        public void putType(Key key, Type value) {
           map.put(key, value);
        }
    
        @SuppressWarnings("unchecked")
        public  Type getType1(Key key, Class typeClass) {
           return (Type)map.get(key); 
        }
    
        @SuppressWarnings("unchecked")
        public  Type getType2(Key key) {
            return (Type) map.get(key);
        }
    }
    

    Clients can type the calls to these methods like this:

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

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

提交回复
热议问题