Consumer mapped Class in HashMap

后端 未结 3 2059
闹比i
闹比i 2020-12-03 06:19

I want to create an IdentityHashMap, Consumer>. Basically, I want to map a type with a method saying what to do with this type.

3条回答
  •  醉梦人生
    2020-12-03 06:49

    It is possible to implement this in a type-safe manner without any unchecked cast. The solution resides in wrapping the Consumer into a more general Consumer that casts and then delegates to the original consumer:

    public class ClassToConsumerMap {
        private final Map, Consumer> map = new IdentityHashMap<>();
    
        public  Consumer put(Class key, Consumer c) {
            return map.put(key, o -> c.accept(key.cast(o)));
        }
    
        public  Consumer get(Class key) {
            return map.get(key);
        }
    }
    
    
    

    Depending on your needs, get() could also simply return a Consumer. This would be necessary if you only know the type at runtime, e.g.

    classToConsumerMap.get(someObject.getClass()).accept(someObject);
    

    I am pretty sure I saw this solution (or something similar) in a talk @ Devoxx Belgium 2016, possibly from Venkat Subramaniam, but I definitively cannot find it back…

    提交回复
    热议问题