1 package com.thoughtworks.xstream.converters.collections; 2 3 import com.thoughtworks.xstream.converters.Converter; 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.util.BitSet ; 10 import java.util.StringTokenizer ; 11 12 18 public class BitSetConverter implements Converter { 19 20 public boolean canConvert(Class type) { 21 return type.equals(BitSet .class); 22 } 23 24 public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { 25 BitSet bitSet = (BitSet ) source; 26 StringBuffer buffer = new StringBuffer (); 27 boolean seenFirst = false; 28 for (int i = 0; i < bitSet.length(); i++) { 29 if (bitSet.get(i)) { 30 if (seenFirst) { 31 buffer.append(','); 32 } else { 33 seenFirst = true; 34 } 35 buffer.append(i); 36 } 37 } 38 writer.setValue(buffer.toString()); 39 } 40 41 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { 42 BitSet result = new BitSet (); 43 StringTokenizer tokenizer = new StringTokenizer (reader.getValue(), ",", false); 44 while (tokenizer.hasMoreTokens()) { 45 int index = Integer.parseInt(tokenizer.nextToken()); 46 result.set(index); 47 } 48 return result; 49 } 50 } 51 | Popular Tags |