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.MarshallingContext; 6 import com.thoughtworks.xstream.converters.UnmarshallingContext; 7 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 8 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 9 10 import java.util.Comparator ; 11 import java.util.TreeSet ; 12 13 19 public class TreeSetConverter extends CollectionConverter { 20 21 public TreeSetConverter(ClassMapper classMapper, String classAttributeIdentifier) { 22 super(classMapper, classAttributeIdentifier); 23 } 24 25 public boolean canConvert(Class type) { 26 return type.equals(TreeSet .class); 27 } 28 29 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 30 TreeSet treeSet = (TreeSet ) source; 31 Comparator comparator = treeSet.comparator(); 32 if (comparator == null) { 33 writer.startNode("no-comparator"); 34 writer.endNode(); 35 } else { 36 writer.startNode("comparator"); 37 writer.addAttribute("class", classMapper.lookupName(comparator.getClass())); 38 context.convertAnother(comparator); 39 writer.endNode(); 40 } 41 super.marshal(source, writer, context); 42 } 43 44 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 45 reader.moveDown(); 46 TreeSet result; 47 if (reader.getNodeName().equals("comparator")) { 48 String comparatorClass = reader.getAttribute("class"); 49 Comparator comparator = (Comparator ) context.convertAnother(null, classMapper.lookupType(comparatorClass)); 50 result = new TreeSet (comparator); 51 } else if (reader.getNodeName().equals("no-comparator")) { 52 result = new TreeSet (); 53 } else { 54 throw new ConversionException("TreeSet does not contain <comparator> element"); 55 } 56 reader.moveUp(); 57 super.populateCollection(reader, context, result); 58 return result; 59 } 60 61 } 62 | Popular Tags |