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.Map ; 23 24 import org.apache.commons.collections.Factory; 25 import org.apache.commons.collections.Transformer; 26 import org.apache.commons.collections.functors.FactoryTransformer; 27 28 58 public class LazyMap 59 extends AbstractMapDecorator 60 implements Map , Serializable { 61 62 63 private static final long serialVersionUID = 7990956402564206740L; 64 65 66 protected final Transformer factory; 67 68 75 public static Map decorate(Map map, Factory factory) { 76 return new LazyMap(map, factory); 77 } 78 79 86 public static Map decorate(Map map, Transformer factory) { 87 return new LazyMap(map, factory); 88 } 89 90 98 protected LazyMap(Map map, Factory factory) { 99 super(map); 100 if (factory == null) { 101 throw new IllegalArgumentException ("Factory must not be null"); 102 } 103 this.factory = FactoryTransformer.getInstance(factory); 104 } 105 106 113 protected LazyMap(Map map, Transformer factory) { 114 super(map); 115 if (factory == null) { 116 throw new IllegalArgumentException ("Factory must not be null"); 117 } 118 this.factory = factory; 119 } 120 121 129 private void writeObject(ObjectOutputStream out) throws IOException { 130 out.defaultWriteObject(); 131 out.writeObject(map); 132 } 133 134 142 private void readObject(ObjectInputStream in) throws IOException , ClassNotFoundException { 143 in.defaultReadObject(); 144 map = (Map ) in.readObject(); 145 } 146 147 public Object get(Object key) { 149 if (map.containsKey(key) == false) { 151 Object value = factory.transform(key); 152 map.put(key, value); 153 return value; 154 } 155 return map.get(key); 156 } 157 158 } 161 | Popular Tags |