import java.util.*; import java.lang.reflect.*; public class ImmutableMap extends ReadOnlyMap { public ImmutableMap(Map map) { // must use a static method here super((Map) ImmutableMap.copyMap(map)); } public ImmutableMap(K[] keys, V[] values) { super(keys,values); } // copy to make sure no mods can happen // but try to keep some class // e.g. for a TreeMap generate a TreeMap // and so on ... static private Map copyMap(Map map) { Class mapClass = map.getClass(); try { // if the input map supports cloning, use it Method m = mapClass.getMethod("clone"); return (Map) m.invoke(map); } catch (Exception e1) { try { // else check whether a constructor taking a map is supported Constructor cons = mapClass.getConstructor(Map.class); return (Map) cons.newInstance(map); } catch (Exception e2) { // if none of the above, simply resort to a HashMap return new HashMap(map); } } } }