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.io.HierarchicalStreamReader; 7 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 8 9 import java.lang.reflect.Array ; 10 import java.util.Iterator ; 11 import java.util.LinkedList ; 12 import java.util.List ; 13 14 20 public class ArrayConverter extends AbstractCollectionConverter { 21 22 public ArrayConverter(ClassMapper classMapper, String classAttributeIdentifier) { 23 super(classMapper, classAttributeIdentifier); 24 } 25 26 public boolean canConvert(Class type) { 27 return type.isArray(); 28 } 29 30 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 31 int length = Array.getLength(source); 32 for (int i = 0; i < length; i++) { 33 Object item = Array.get(source, i); 34 writeItem(item, context, writer); 35 } 36 } 37 38 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 39 List items = new LinkedList (); 41 while (reader.hasMoreChildren()) { 42 reader.moveDown(); 43 Object item = readItem(reader, context, null); items.add(item); 45 reader.moveUp(); 46 } 47 Object array = Array.newInstance(context.getRequiredType().getComponentType(), items.size()); 51 int i = 0; 52 for (Iterator iterator = items.iterator(); iterator.hasNext();) { 53 Object item = (Object ) iterator.next(); 54 Array.set(array, i, item); 55 i++; 56 } 57 return array; 58 } 59 } 60 | Popular Tags |