Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 generic map of functions

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.

like image 920
Christian Bongiorno Avatar asked May 06 '15 21:05

Christian Bongiorno


1 Answers

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);
  }
}
like image 169
Raffaele Avatar answered Oct 07 '22 01:10

Raffaele