KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > mapper > EnumMapper


1 package com.thoughtworks.xstream.mapper;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4 import com.thoughtworks.xstream.core.JVM;
5
6 /**
7  * Mapper that handles the special case of polymorphic enums in Java 1.5. This renames MyEnum$1 to MyEnum making it
8  * less bloaty in the XML and avoiding the need for an alias per enum value to be specified.
9  *
10  * @author Joe Walnes
11  */

12 public class EnumMapper extends MapperWrapper {
13
14     // Dynamically try to load Enum class. Pre JDK1.5 will silently fail.
15
private static JVM jvm = new JVM();
16     private static final Class JavaDoc enumClass = jvm.loadClass("java.lang.Enum");
17
18     private static final boolean active = enumClass != null;
19
20     private static final Class JavaDoc enumSetClass = active ? jvm.loadClass("java.util.EnumSet") : null;
21
22     public EnumMapper(ClassMapper wrapped) {
23         super(wrapped);
24     }
25
26     public String JavaDoc serializedClass(Class JavaDoc type) {
27         if (!active) {
28             return super.serializedClass(type);
29         } else {
30             if (enumClass.isAssignableFrom(type) && type.getSuperclass() != enumClass) {
31                 return super.serializedClass(type.getSuperclass());
32             } else if (enumSetClass.isAssignableFrom(type)) {
33                 return super.serializedClass(enumSetClass);
34             } else {
35                 return super.serializedClass(type);
36             }
37         }
38     }
39
40 }
41
Popular Tags