KickJava   Java API By Example, From Geeks To Geeks.

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


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.Converter;
8 import com.thoughtworks.xstream.converters.MarshallingContext;
9 import com.thoughtworks.xstream.converters.UnmarshallingContext;
10 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
11 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
12
13 /**
14  * Converter for JDK 1.5 enums. Combined with EnumMapper this also deals with polymorphic enums.
15  *
16  * @author Eric Snell
17  * @author Bryan Coleman
18  */

19 public class EnumConverter implements Converter {
20
21     public boolean canConvert(Class JavaDoc type) {
22         return type.isEnum() || Enum JavaDoc.class.isAssignableFrom(type);
23     }
24
25     public void marshal(Object JavaDoc source, HierarchicalStreamWriter writer, MarshallingContext context) {
26         writer.setValue(((Enum JavaDoc) source).name());
27     }
28
29     public Object JavaDoc unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
30         Class JavaDoc type = context.getRequiredType();
31         if (type.getSuperclass() != Enum JavaDoc.class) {
32             type = type.getSuperclass(); // polymorphic enums
33
}
34         return Enum.valueOf(type, reader.getValue());
35     }
36
37 }
38
Popular Tags