Not sure if this is even possible; I admit I am not as good at generics as I would like to be.
Basically, I want to create a map of class -> function where the class used for the key is the class of the input to the function, like such (not legal syntax):
public static Map<Class<T>,Function<T,Expression>> STUFF = new HashMap<>();
{
STUFF.put(List.class, ListExpression::new);
STUFF.put(String.class, StringExpression::new);// this constructor must take string
}
so that if I do:
Function<String,Expression> e = STUFF.get(o.getClass());
Expression ex = e.apply(o);
It gets the types right for me.
It can't be done. Every time you want Map<Class<T>, SomeType<T>>
, ie associating a class with a parameterized type somehow related to the class in the key, it can't be done. This is because the key type, Class<T>
must be shared among all entries as per the Map<K, V>
definition.
What remains is the practical alternative to have a Map<Class<?>, SomeType<?>>
, encapsulate this map in a private field and check constraints when putting items in the map. Something like
public class StuffManager {
private final Map<Class<?>, Consumer<?>> stuff = new HashMap<>();
public <T> void register(Class<T> key, Consumer<? super T> val) {
stuff.put(key, val);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With