1 5 package com.thoughtworks.xstream.converters.enums; 6 7 import com.thoughtworks.xstream.converters.Converter; 8 import com.thoughtworks.xstream.converters.MarshallingContext; 9 import com.thoughtworks.xstream.converters.UnmarshallingContext; 10 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 11 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 12 import com.thoughtworks.xstream.mapper.Mapper; 13 import com.thoughtworks.xstream.core.util.Fields; 14 15 import java.lang.reflect.Field ; 16 import java.util.EnumSet ; 17 import java.util.Iterator ; 18 19 24 public class EnumSetConverter implements Converter { 25 26 private final Field typeField; 27 private final Mapper mapper; 28 29 public EnumSetConverter(Mapper mapper) { 30 this.mapper = mapper; 31 typeField = Fields.find(EnumSet .class, "elementType"); 32 } 33 34 public boolean canConvert(Class type) { 35 return EnumSet .class.isAssignableFrom(type); 36 } 37 38 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 39 EnumSet set = (EnumSet ) source; 40 Class enumTypeForSet = (Class ) Fields.read(typeField, set); 41 writer.addAttribute(mapper.attributeForEnumType(), mapper.serializedClass(enumTypeForSet)); 42 writer.setValue(joinEnumValues(set)); 43 } 44 45 private String joinEnumValues(EnumSet set) { 46 boolean seenFirst = false; 47 StringBuffer result = new StringBuffer (); 48 for (Iterator iterator = set.iterator(); iterator.hasNext();) { 49 Enum value = (Enum ) iterator.next(); 50 if (seenFirst) { 51 result.append(','); 52 } else { 53 seenFirst = true; 54 } 55 result.append(value.name()); 56 } 57 return result.toString(); 58 } 59 60 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 61 Class enumTypeForSet = mapper.realClass(reader.getAttribute(mapper.attributeForEnumType())); 62 EnumSet set = EnumSet.noneOf(enumTypeForSet); 63 String [] enumValues = reader.getValue().split(","); 64 for (int i = 0; i < enumValues.length; i++) { 65 String enumValue = enumValues[i]; 66 set.add(Enum.valueOf(enumTypeForSet, enumValue)); 67 } 68 return set; 69 } 70 71 } 72 | Popular Tags |