1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.beanutils.converters;
18
19 /***
20 * {@link org.apache.commons.beanutils.Converter} implementaion that handles conversion
21 * to and from <b>java.lang.Class</b> objects.
22 * <p>
23 * The class will be loaded from the thread context class
24 * loader (if it exists); otherwise the class loader that loaded this class
25 * will be used.
26 * <p>
27 * Can be configured to either return a <i>default value</i> or throw a
28 * <code>ConversionException</code> if a conversion error occurs.
29 *
30 * @author Tomas Viberg
31 * @version $Revision: 555845 $ $Date: 2007-07-13 03:52:05 +0100 (Fri, 13 Jul 2007) $
32 * @since 1.4
33 */
34 public final class ClassConverter extends AbstractConverter {
35
36 /***
37 * Construct a <b>java.lang.Class</b> <i>Converter</i> that throws
38 * a <code>ConversionException</code> if an error occurs.
39 */
40 public ClassConverter() {
41 super(Class.class);
42 }
43
44 /***
45 * Construct a <b>java.lang.Class</b> <i>Converter</i> that returns
46 * a default value if an error occurs.
47 *
48 * @param defaultValue The default value to be returned
49 * if the value to be converted is missing or an error
50 * occurs converting the value.
51 */
52 public ClassConverter(Object defaultValue) {
53 super(Class.class, defaultValue);
54 }
55
56 /***
57 * <p>Convert a java.lang.Class or object into a String.</p>
58 *
59 * @param value The input value to be converted
60 * @return the converted String value.
61 */
62 protected String convertToString(Object value) {
63 return (value instanceof Class) ? ((Class)value).getName() : value.toString();
64 }
65
66 /***
67 * <p>Convert the input object into a java.lang.Class.</p>
68 *
69 * @param type Data type to which this value should be converted.
70 * @param value The input value to be converted.
71 * @return The converted value.
72 * @throws Throwable if an error occurs converting to the specified type
73 */
74 protected Object convertToType(Class type, Object value) throws Throwable {
75 ClassLoader classLoader =
76 Thread.currentThread().getContextClassLoader();
77 if (classLoader != null) {
78 try {
79 return (classLoader.loadClass(value.toString()));
80 } catch (ClassNotFoundException ex) {
81
82
83 }
84 }
85
86
87 classLoader = ClassConverter.class.getClassLoader();
88 return (classLoader.loadClass(value.toString()));
89 }
90
91 }