1 package com.thoughtworks.xstream.converters.collections; 2 3 import com.thoughtworks.xstream.alias.ClassMapper; 4 import com.thoughtworks.xstream.converters.MarshallingContext; 5 import com.thoughtworks.xstream.converters.UnmarshallingContext; 6 import com.thoughtworks.xstream.core.JVM; 7 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 8 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 9 10 import java.util.*; 11 12 21 public class CollectionConverter extends AbstractCollectionConverter { 22 23 public CollectionConverter(ClassMapper classMapper, String classAttributeIdentifier) { 24 super(classMapper, classAttributeIdentifier); 25 } 26 27 public boolean canConvert(Class type) { 28 return type.equals(ArrayList.class) 29 || type.equals(HashSet.class) 30 || type.equals(LinkedList.class) 31 || type.equals(Vector.class) 32 || (JVM.is14() && type.getName().equals("java.util.LinkedHashSet")); 33 } 34 35 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 36 Collection collection = (Collection) source; 37 for (Iterator iterator = collection.iterator(); iterator.hasNext();) { 38 Object item = iterator.next(); 39 writeItem(item, context, writer); 40 } 41 } 42 43 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 44 Collection collection = (Collection) createCollection(context.getRequiredType()); 45 populateCollection(reader, context, collection); 46 return collection; 47 } 48 49 protected void populateCollection(HierarchicalStreamReader reader, UnmarshallingContext context, Collection collection) { 50 while (reader.hasMoreChildren()) { 51 reader.moveDown(); 52 Object item = readItem(reader, context, collection); 53 collection.add(item); 54 reader.moveUp(); 55 } 56 } 57 58 } 59 | Popular Tags |