I want to create an IdentityHashMap
. Basically, I want to map a type with a method saying what to do with this type.
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
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…