I'm trying to write a simple utility function to get a value from a Map and, if it's not found to create a new value class and put that in the map.
It seems though very difficult to get the classes of the map's key and value at runtime and the best I can come up with is something horrible along the following lines.
Is there a better way?
private Object getOrCreate( Map<Object, Object> map, Object key, Class<?> mapValueClass ) {
Object value = map.get( key );
if (value == null) {
Constructor<?> con = mapValueClass.getConstructor( key.getClass() );
value = con.newInstance( key );
map.put( key, value );
}
return value;
}