1 16 package org.apache.commons.collections.map; 17 18 import java.io.IOException ; 19 import java.io.ObjectInputStream ; 20 import java.io.ObjectOutputStream ; 21 import java.io.Serializable ; 22 import java.util.HashMap ; 23 import java.util.Map ; 24 25 import org.apache.commons.collections.Factory; 26 import org.apache.commons.collections.Transformer; 27 import org.apache.commons.collections.functors.ConstantTransformer; 28 import org.apache.commons.collections.functors.FactoryTransformer; 29 30 65 public class DefaultedMap 66 extends AbstractMapDecorator 67 implements Map , Serializable { 68 69 70 private static final long serialVersionUID = 19698628745827L; 71 72 73 protected final Object value; 74 75 85 public static Map decorate(Map map, Object defaultValue) { 86 if (defaultValue instanceof Transformer) { 87 defaultValue = ConstantTransformer.getInstance(defaultValue); 88 } 89 return new DefaultedMap(map, defaultValue); 90 } 91 92 102 public static Map decorate(Map map, Factory factory) { 103 if (factory == null) { 104 throw new IllegalArgumentException ("Factory must not be null"); 105 } 106 return new DefaultedMap(map, FactoryTransformer.getInstance(factory)); 107 } 108 109 120 public static Map decorate(Map map, Transformer factory) { 121 if (factory == null) { 122 throw new IllegalArgumentException ("Transformer must not be null"); 123 } 124 return new DefaultedMap(map, factory); 125 } 126 127 137 public DefaultedMap(Object defaultValue) { 138 super(new HashMap ()); 139 if (defaultValue instanceof Transformer) { 140 defaultValue = ConstantTransformer.getInstance(defaultValue); 141 } 142 this.value = defaultValue; 143 } 144 145 152 protected DefaultedMap(Map map, Object value) { 153 super(map); 154 this.value = value; 155 } 156 157 164 private void writeObject(ObjectOutputStream out) throws IOException { 165 out.defaultWriteObject(); 166 out.writeObject(map); 167 } 168 169 176 private void readObject(ObjectInputStream in) throws IOException , ClassNotFoundException { 177 in.defaultReadObject(); 178 map = (Map ) in.readObject(); 179 } 180 181 public Object get(Object key) { 183 if (map.containsKey(key) == false) { 185 if (value instanceof Transformer) { 186 return ((Transformer) value).transform(key); 187 } 188 return value; 189 } 190 return map.get(key); 191 } 192 193 } 196 | Popular Tags |