1 package com.thoughtworks.xstream.mapper; 2 3 import com.thoughtworks.xstream.alias.ClassMapper; 4 import com.thoughtworks.xstream.alias.CannotResolveClassException; 5 6 12 public class ArrayMapper extends MapperWrapper { 13 14 public ArrayMapper(ClassMapper wrapped) { 15 super(wrapped); 16 } 17 18 public String serializedClass(Class type) { 19 StringBuffer arraySuffix = new StringBuffer (); 20 while (type.isArray()) { 21 type = type.getComponentType(); 22 arraySuffix.append("-array"); 23 } 24 String name = super.serializedClass(type); 25 if (arraySuffix.length() > 0) { 26 return name + arraySuffix; 27 } else { 28 return name; 29 } 30 } 31 32 public Class realClass(String elementName) { 33 int dimensions = 0; 34 35 while (elementName.endsWith("-array")) { 37 elementName = elementName.substring(0, elementName.length() - 6); dimensions++; 39 } 40 41 if (dimensions > 0) { 42 Class componentType = primitiveClassNamed(elementName); 43 if (componentType == null) { 44 componentType = super.realClass(elementName); 45 } 46 try { 47 return arrayType(dimensions, componentType); 48 } catch (ClassNotFoundException e) { 49 throw new CannotResolveClassException(elementName + " : " + e.getMessage()); 50 } 51 } else { 52 return super.realClass(elementName); 53 } 54 } 55 56 private Class arrayType(int dimensions, Class componentType) throws ClassNotFoundException { 57 StringBuffer className = new StringBuffer (); 58 for (int i = 0; i < dimensions; i++) { 59 className.append('['); 60 } 61 if (componentType.isPrimitive()) { 62 className.append(charThatJavaUsesToRepresentPrimitiveArrayType(componentType)); 63 return Class.forName(className.toString()); 64 } else { 65 className.append('L').append(componentType.getName()).append(';'); 66 return Class.forName(className.toString(), false, componentType.getClassLoader()); 67 } 68 } 69 70 private Class primitiveClassNamed(String name) { 71 return 72 name.equals("void") ? Void.TYPE : 73 name.equals("boolean") ? Boolean.TYPE : 74 name.equals("byte") ? Byte.TYPE : 75 name.equals("char") ? Character.TYPE : 76 name.equals("short") ? Short.TYPE : 77 name.equals("int") ? Integer.TYPE : 78 name.equals("long") ? Long.TYPE : 79 name.equals("float") ? Float.TYPE : 80 name.equals("double") ? Double.TYPE : 81 null; 82 } 83 84 private char charThatJavaUsesToRepresentPrimitiveArrayType(Class primvCls) { 85 return 86 (primvCls == boolean.class) ? 'Z' : 87 (primvCls == byte.class) ? 'B' : 88 (primvCls == char.class) ? 'C' : 89 (primvCls == short.class) ? 'S' : 90 (primvCls == int.class) ? 'I' : 91 (primvCls == long.class) ? 'J' : 92 (primvCls == float.class) ? 'F' : 93 (primvCls == double.class) ? 'D' : 94 0; 95 } 96 97 } 98 | Popular Tags |