I'm returning an unmodifiable map from a method. How do I make sure that any code that tries to modify the returned map will get a compile time error, as opposed to a run time error?
My class:
public class Foo
{
private final Map<String, Bar> aMap;
public Foo()
{
...
}
public Map<String, Bar> getMap(){
return Collections.unmodifiableMap(aMap);
}
}
I want this to create a compile time error:
Foo foo = new Foo();
Map<String, Bar> m = foo.getMap();
m.put('key',null); // user should be notified that the map is unmodifiable here, not at run time
Can I change the return type? Can I add an appropriate annotation?
You could create a class like
class ReadOnlyMap<K, V> {
private final Map<K, V> map;
public ReadOnlyMap(Map<K, V> map) {
this.map = map;
}
public V get(Object key) {
return map.get(key);
}
// also implement size() method
// and everything else you want to expose
}
and use it as the return type of your method. Then your method would be
public ReadOnlyMap<String, Bar> getMap() {
return new ReadOnlyMap(aMap);
}
Beware that this won't hinder the caller to mutate the value objects, if they're not instances of immutable classes.