KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > enums > EnumMapConverter


1 // ***** READ THIS *****
2
// This class will only compile with JDK 1.5.0 or above as it test Java enums.
3
// If you are using an earlier version of Java, just don't try to build this class. XStream should work fine without it.
4

5 package com.thoughtworks.xstream.converters.enums;
6
7 import com.thoughtworks.xstream.converters.collections.MapConverter;
8 import com.thoughtworks.xstream.converters.MarshallingContext;
9 import com.thoughtworks.xstream.converters.UnmarshallingContext;
10 import com.thoughtworks.xstream.mapper.Mapper;
11 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
12 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
13 import com.thoughtworks.xstream.core.util.Fields;
14
15 import java.util.EnumMap JavaDoc;
16 import java.lang.reflect.Field JavaDoc;
17
18 /**
19  * Serializes an Java 5 EnumMap, including the type of Enum it's for.
20  *
21  * @author Joe Walnes
22  */

23 public class EnumMapConverter extends MapConverter {
24
25     private final Field JavaDoc typeField;
26
27     public EnumMapConverter(Mapper mapper) {
28         super(mapper);
29         typeField = Fields.find(EnumMap JavaDoc.class, "keyType");
30     }
31
32     public boolean canConvert(Class JavaDoc type) {
33         return type == EnumMap JavaDoc.class;
34     }
35
36     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
37         Class JavaDoc type = (Class JavaDoc) Fields.read(typeField, source);
38         writer.addAttribute(mapper().attributeForEnumType(), mapper().serializedClass(type));
39         super.marshal(source, writer, context);
40     }
41
42     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
43         Class JavaDoc type = mapper().realClass(reader.getAttribute(mapper().attributeForEnumType()));
44         EnumMap JavaDoc map = new EnumMap JavaDoc(type);
45         populateMap(reader, context, map);
46         return map;
47     }
48 }
49
Popular Tags