A Formatter<T>
knows how to format T
to string:
public interface Formatter<T> {
String format(final T t);
}
I would like to have a Map
of formatters, one for Integer
, one for Date
etc:
Map<Class, Formatter> formatters;
The intended use would be:
formatters.put(Integer.class, new Formatter<Integer>() {
public String format(Integer i) {
return i.toString;
}
});
Is there some way to enforce that the key-values will agree on the Class
type? That if I say put(Integer.class, new Formatter<Integer>(){...})
it will work but put(Integer.class, new Formatter<Date>(){...})
will not?
What I am trying now is to use ? as the type:
Map<Class<?>, Formatter<?>> formatters;
But then I cannot use formatters inside this map:
Object obj = Integer.valueOf(15);
formatters.get(obj.getClass()).format(obj);
Error: The method format(capture#3-of ?) in the type Formatter<capture#3-of ?> is not applicable for the arguments (Object)
Any clarification would be welcome.