KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.thoughtworks.xstream.mapper;
2
3 import com.thoughtworks.xstream.alias.ClassMapper;
4
5 import java.util.Map JavaDoc;
6 import java.util.Collections JavaDoc;
7 import java.util.HashMap JavaDoc;
8
9 /**
10  * Mapper that allows a fully qualified class name to be replaced with a shorter alias.
11  *
12  * @author Joe Walnes
13  */

14 public class ClassAliasingMapper extends MapperWrapper {
15
16     protected final Map JavaDoc typeToNameMap = Collections.synchronizedMap(new HashMap JavaDoc());
17     protected final Map JavaDoc nameToTypeMap = Collections.synchronizedMap(new HashMap JavaDoc());
18
19     public ClassAliasingMapper(ClassMapper wrapped) {
20         super(wrapped);
21     }
22
23     public void addClassAlias(String JavaDoc name, Class JavaDoc type) {
24         nameToTypeMap.put(name, type.getName());
25         typeToNameMap.put(type.getName(), name);
26     }
27
28     public String JavaDoc serializedClass(Class JavaDoc type) {
29         String JavaDoc name = super.serializedClass(type);
30         String JavaDoc alias = (String JavaDoc) typeToNameMap.get(type.getName());
31         if (alias != null) {
32             return alias;
33         } else {
34             return name;
35         }
36     }
37
38     public Class JavaDoc realClass(String JavaDoc elementName) {
39         if (elementName.equals("null")) { // TODO: This is probably the wrong place for this.
40
return null;
41         }
42
43         String JavaDoc mappedName = (String JavaDoc) nameToTypeMap.get(mapNameFromXML(elementName));
44
45         if (mappedName != null) {
46             elementName = mappedName;
47         }
48
49         return super.realClass(elementName);
50     }
51
52 }
53
Popular Tags