01: /*
02: * Copyright (C) 2004, 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 04. April 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.extended;
13:
14: import com.thoughtworks.xstream.converters.ConversionException;
15: import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
16:
17: /**
18: * Converts a java.lang.Class to XML.
19: *
20: * @author Aslak Hellesøy
21: * @author Joe Walnes
22: * @author Matthew Sandoz
23: * @author Jörg Schaible
24: */
25: public class JavaClassConverter extends AbstractSingleValueConverter {
26:
27: private ClassLoader classLoader;
28:
29: /**
30: * @deprecated As of 1.1.1 - use other constructor and explicitly supply a ClassLoader.
31: */
32: public JavaClassConverter() {
33: this (Thread.currentThread().getContextClassLoader());
34: }
35:
36: public JavaClassConverter(ClassLoader classLoader) {
37: this .classLoader = classLoader;
38: }
39:
40: public boolean canConvert(Class clazz) {
41: return Class.class.equals(clazz); // :)
42: }
43:
44: public String toString(Object obj) {
45: return ((Class) obj).getName();
46: }
47:
48: public Object fromString(String str) {
49: try {
50: return loadClass(str);
51: } catch (ClassNotFoundException e) {
52: throw new ConversionException("Cannot load java class "
53: + str, e);
54: }
55: }
56:
57: private Class loadClass(String className)
58: throws ClassNotFoundException {
59: Class resultingClass = primitiveClassForName(className);
60: if (resultingClass != null) {
61: return resultingClass;
62: }
63: int dimension;
64: for (dimension = 0; className.charAt(dimension) == '['; ++dimension)
65: ;
66: if (dimension > 0) {
67: final ClassLoader classLoaderToUse;
68: if (className.charAt(dimension) == 'L') {
69: String componentTypeName = className.substring(
70: dimension + 1, className.length() - 1);
71: classLoaderToUse = classLoader.loadClass(
72: componentTypeName).getClassLoader();
73: } else {
74: classLoaderToUse = null;
75: }
76: return Class.forName(className, false, classLoaderToUse);
77: }
78: return classLoader.loadClass(className);
79: }
80:
81: /**
82: * Lookup table for primitive types.
83: */
84: private Class primitiveClassForName(String name) {
85: return name.equals("void") ? Void.TYPE
86: : name.equals("boolean") ? Boolean.TYPE : name
87: .equals("byte") ? Byte.TYPE : name
88: .equals("char") ? Character.TYPE : name
89: .equals("short") ? Short.TYPE : name
90: .equals("int") ? Integer.TYPE : name
91: .equals("long") ? Long.TYPE : name
92: .equals("float") ? Float.TYPE : name
93: .equals("double") ? Double.TYPE : null;
94: }
95:
96: }
|