How to get or create new map entry
<p>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.</p>

<p>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.</p>

<p>Is there a better way?</p>

<pre><code>private Object getOrCreate( Map&lt;Object, Object&gt; map, Object key, Class&lt;?&gt; mapValueClass ) {
    Object value = map.get( key );      

    if (value == null) {                     
        Constructor&lt;?&gt; con = mapValueClass.getConstructor( key.getClass() );
        value = con.newInstance( key );  
        map.put( key, value );               
    }

    return value;
}
</code></pre>