01: /*
02: * Copyright (C) 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 18. March 2005 by Joe Walnes
11: */
12:
13: // ***** READ THIS *****
14: // This class will only compile with JDK 1.5.0 or above as it test Java enums.
15: // If you are using an earlier version of Java, just don't try to build this class. XStream should work fine without it.
16: package com.thoughtworks.xstream.converters.enums;
17:
18: import com.thoughtworks.xstream.converters.Converter;
19: import com.thoughtworks.xstream.converters.MarshallingContext;
20: import com.thoughtworks.xstream.converters.UnmarshallingContext;
21: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
22: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
23:
24: /**
25: * Converter for JDK 1.5 enums. Combined with EnumMapper this also deals with polymorphic enums.
26: *
27: * @author Eric Snell
28: * @author Bryan Coleman
29: */
30: public class EnumConverter implements Converter {
31:
32: public boolean canConvert(Class type) {
33: return type.isEnum() || Enum.class.isAssignableFrom(type);
34: }
35:
36: public void marshal(Object source, HierarchicalStreamWriter writer,
37: MarshallingContext context) {
38: writer.setValue(((Enum) source).name());
39: }
40:
41: public Object unmarshal(HierarchicalStreamReader reader,
42: UnmarshallingContext context) {
43: Class type = context.getRequiredType();
44: // TODO: There's no test case for polymorphic enums.
45: if (type.getSuperclass() != Enum.class) {
46: type = type.getSuperclass(); // polymorphic enums
47: }
48: return Enum.valueOf(type, reader.getValue());
49: }
50:
51: }
|