1 package com.thoughtworks.xstream.converters.collections; 2 3 import com.thoughtworks.xstream.alias.ClassMapper; 4 import com.thoughtworks.xstream.converters.ConversionException; 5 import com.thoughtworks.xstream.converters.Converter; 6 import com.thoughtworks.xstream.converters.MarshallingContext; 7 import com.thoughtworks.xstream.converters.UnmarshallingContext; 8 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 9 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 10 11 21 public abstract class AbstractCollectionConverter implements Converter { 22 protected ClassMapper classMapper; 23 protected String classAttributeIdentifier; 24 25 public abstract boolean canConvert(Class type); 26 27 public AbstractCollectionConverter(ClassMapper classMapper, String classAttributeIdentifier) { 28 this.classMapper = classMapper; 29 this.classAttributeIdentifier = classAttributeIdentifier; 30 } 31 32 public abstract void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context); 33 34 public abstract Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context); 35 36 protected void writeItem(Object item, MarshallingContext context, HierarchicalStreamWriter writer) { 37 if (item == null) { 38 writer.startNode(classMapper.lookupName(ClassMapper.Null.class)); 40 writer.endNode(); 41 } else { 42 writer.startNode(classMapper.lookupName(item.getClass())); 43 context.convertAnother(item); 44 writer.endNode(); 45 } 46 } 47 48 protected Object readItem(HierarchicalStreamReader reader, UnmarshallingContext context, Object current) { 49 String classAttribute = reader.getAttribute(classAttributeIdentifier); 50 Class type; 51 if (classAttribute == null) { 52 type = classMapper.lookupType(reader.getNodeName()); 53 } else { 54 type = classMapper.lookupType(classAttribute); 55 } 56 return context.convertAnother(current, type); 57 } 58 59 protected Object createCollection(Class type) { 60 Class defaultType = classMapper.lookupDefaultType(type); 61 try { 62 return defaultType.newInstance(); 63 } catch (InstantiationException e) { 64 throw new ConversionException("Cannot instantiate " + defaultType.getName(), e); 65 } catch (IllegalAccessException e) { 66 throw new ConversionException("Cannot instantiate " + defaultType.getName(), e); 67 } 68 } 69 } 70 | Popular Tags |