1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.tiles.request.reflect;
22
23 import java.beans.BeanInfo;
24 import java.beans.Introspector;
25 import java.beans.PropertyDescriptor;
26 import java.util.Map;
27
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31
32
33
34
35
36
37 public final class ClassUtil {
38
39
40
41
42 private ClassUtil() {
43 }
44
45
46
47
48
49
50
51
52
53
54
55
56 public static <T> Class<? extends T> getClass(String className,
57 Class<T> baseClass) throws ClassNotFoundException {
58 ClassLoader classLoader = Thread.currentThread()
59 .getContextClassLoader();
60 if (classLoader == null) {
61 classLoader = ClassUtil.class.getClassLoader();
62 }
63 return Class.forName(className, true, classLoader)
64 .asSubclass(baseClass);
65 }
66
67
68
69
70
71
72
73
74
75
76 public static Object instantiate(String className) {
77 return instantiate(className, false);
78 }
79
80
81
82
83
84
85
86
87
88
89
90
91 public static Object instantiate(String className, boolean returnNull) {
92 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
93 if (classLoader == null) {
94 classLoader = ClassUtil.class.getClassLoader();
95 }
96 try {
97 Class<? extends Object> namedClass = getClass(className, Object.class);
98 return namedClass.newInstance();
99 } catch (ClassNotFoundException e) {
100 if (returnNull) {
101 return null;
102 }
103 throw new CannotInstantiateObjectException(
104 "Unable to resolve factory class: '" + className + "'", e);
105 } catch (IllegalAccessException e) {
106 throw new CannotInstantiateObjectException(
107 "Unable to access factory class: '" + className + "'", e);
108 } catch (InstantiationException e) {
109 throw new CannotInstantiateObjectException(
110 "Unable to instantiate factory class: '"
111 + className
112 + "'. Make sure that this class has a default constructor",
113 e);
114 }
115 }
116
117
118
119
120
121
122
123
124 public static void collectBeanInfo(Class<?> clazz,
125 Map<String, PropertyDescriptor> name2descriptor) {
126 Logger log = LoggerFactory.getLogger(ClassUtil.class);
127 BeanInfo info = null;
128 try {
129 info = Introspector.getBeanInfo(clazz);
130 } catch (Exception ex) {
131 if (log.isDebugEnabled()) {
132 log.debug("Cannot inspect class " + clazz, ex);
133 }
134 }
135 if (info == null) {
136 return;
137 }
138 for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
139 pd.setValue("type", pd.getPropertyType());
140 pd.setValue("resolvableAtDesignTime", Boolean.TRUE);
141 name2descriptor.put(pd.getName(), pd);
142 }
143 }
144 }