1 package org.codehaus.plexus.interpolation.reflection;
2
3 /* ====================================================================
4 * Copyright 2001-2004 The Apache Software Foundation.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ====================================================================
18 */
19
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Modifier;
22 import java.util.Hashtable;
23 import java.util.Map;
24
25 /**
26 * <b>NOTE:</b> This class was copied from plexus-utils, to allow this library
27 * to stand completely self-contained.
28 * <p>A cache of introspection information for a specific class instance.
29 * Keys {@link Method} objects by a concatenation of the
30 * method name and the names of classes that make up the parameters.</p>
31 *
32 * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
33 * @author <a href="mailto:bob@werken.com">Bob McWhirter</a>
34 * @author <a href="mailto:szegedia@freemail.hu">Attila Szegedi</a>
35 * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
36 */
37 public class ClassMap {
38 private static final class CacheMiss {}
39
40 private static final CacheMiss CACHE_MISS = new CacheMiss();
41 private static final Object OBJECT = new Object();
42
43 /**
44 * Class passed into the constructor used to as
45 * the basis for the Method map.
46 */
47 private Class<?> clazz;
48
49 /**
50 * Cache of Methods, or CACHE_MISS, keyed by method
51 * name and actual arguments used to find it.
52 */
53 private Map<String, Object> methodCache = new Hashtable<String, Object>();
54
55 private MethodMap methodMap = new MethodMap();
56
57 /**
58 * Standard constructor
59 * @param clazz The class to be analyzed.
60 */
61 public ClassMap(Class<?> clazz) {
62 this.clazz = clazz;
63 populateMethodCache();
64 }
65
66 /**
67 * @return the class object whose methods are cached by this map.
68 */
69 Class<?> getCachedClass() {
70 return clazz;
71 }
72
73 /**
74 * <p>Find a Method using the methodKey
75 * provided.</p>
76 * <p>Look in the methodMap for an entry. If found,
77 * it'll either be a CACHE_MISS, in which case we
78 * simply give up, or it'll be a Method, in which
79 * case, we return it.</p>
80 * <p>If nothing is found, then we must actually go
81 * and introspect the method from the MethodMap.</p>
82 * @param name name of the method.
83 * @param params The parameters for the method.
84 * @return {@link Method}.
85 * @throws MethodMap.AmbiguousException in case of an error.
86 */
87 public Method findMethod(String name, Object[] params) throws MethodMap.AmbiguousException {
88 String methodKey = makeMethodKey(name, params);
89 Object cacheEntry = methodCache.get(methodKey);
90
91 if (cacheEntry == CACHE_MISS) {
92 return null;
93 }
94
95 if (cacheEntry == null) {
96 try {
97 cacheEntry = methodMap.find(name, params);
98 } catch (MethodMap.AmbiguousException ae) {
99 /*
100 * that's a miss :)
101 */
102
103 methodCache.put(methodKey, CACHE_MISS);
104
105 throw ae;
106 }
107
108 if (cacheEntry == null) {
109 methodCache.put(methodKey, CACHE_MISS);
110 } else {
111 methodCache.put(methodKey, cacheEntry);
112 }
113 }
114
115 // Yes, this might just be null.
116
117 return (Method) cacheEntry;
118 }
119
120 /**
121 * Populate the Map of direct hits. These
122 * are taken from all the public methods
123 * that our class provides.
124 */
125 private void populateMethodCache() {
126 /*
127 * get all publicly accessible methods
128 */
129
130 Method[] methods = getAccessibleMethods(clazz);
131
132 /*
133 * map and cache them
134 */
135
136 for (Method method : methods) {
137 /*
138 * now get the 'public method', the method declared by a
139 * public interface or class. (because the actual implementing
140 * class may be a facade...
141 */
142
143 Method publicMethod = getPublicMethod(method);
144
145 /*
146 * it is entirely possible that there is no public method for
147 * the methods of this class (i.e. in the facade, a method
148 * that isn't on any of the interfaces or superclass
149 * in which case, ignore it. Otherwise, map and cache
150 */
151
152 if (publicMethod != null) {
153 methodMap.add(publicMethod);
154 methodCache.put(makeMethodKey(publicMethod), publicMethod);
155 }
156 }
157 }
158
159 /**
160 * Make a methodKey for the given method using
161 * the concatenation of the name and the
162 * types of the method parameters.
163 */
164 private String makeMethodKey(Method method) {
165 Class<?>[] parameterTypes = method.getParameterTypes();
166
167 StringBuilder methodKey = new StringBuilder(method.getName());
168
169 for (Class<?> parameterType : parameterTypes) {
170 /*
171 * If the argument type is primitive then we want
172 * to convert our primitive type signature to the
173 * corresponding Object type so introspection for
174 * methods with primitive types will work correctly.
175 */
176 if (parameterType.isPrimitive()) {
177 if (parameterType.equals(Boolean.TYPE)) {
178 methodKey.append("java.lang.Boolean");
179 } else if (parameterType.equals(Byte.TYPE)) {
180 methodKey.append("java.lang.Byte");
181 } else if (parameterType.equals(Character.TYPE)) {
182 methodKey.append("java.lang.Character");
183 } else if (parameterType.equals(Double.TYPE)) {
184 methodKey.append("java.lang.Double");
185 } else if (parameterType.equals(Float.TYPE)) {
186 methodKey.append("java.lang.Float");
187 } else if (parameterType.equals(Integer.TYPE)) {
188 methodKey.append("java.lang.Integer");
189 } else if (parameterType.equals(Long.TYPE)) {
190 methodKey.append("java.lang.Long");
191 } else if (parameterType.equals(Short.TYPE)) {
192 methodKey.append("java.lang.Short");
193 }
194 } else {
195 methodKey.append(parameterType.getName());
196 }
197 }
198
199 return methodKey.toString();
200 }
201
202 private static String makeMethodKey(String method, Object[] params) {
203 if (params.length == 0) {
204 return method;
205 }
206
207 StringBuilder methodKey = new StringBuilder().append(method);
208
209 for (Object arg : params) {
210 if (arg == null) {
211 arg = OBJECT;
212 }
213
214 methodKey.append(arg.getClass().getName());
215 }
216
217 return methodKey.toString();
218 }
219
220 /**
221 * Retrieves public methods for a class. In case the class is not
222 * public, retrieves methods with same signature as its public methods
223 * from public superclasses and interfaces (if they exist). Basically
224 * upcasts every method to the nearest acccessible method.
225 */
226 private static Method[] getAccessibleMethods(Class<?> clazz) {
227 Method[] methods = clazz.getMethods();
228
229 /*
230 * Short circuit for the (hopefully) majority of cases where the
231 * clazz is public
232 */
233
234 if (Modifier.isPublic(clazz.getModifiers())) {
235 return methods;
236 }
237
238 /*
239 * No luck - the class is not public, so we're going the longer way.
240 */
241
242 MethodInfo[] methodInfos = new MethodInfo[methods.length];
243
244 for (int i = methods.length; i-- > 0; ) {
245 methodInfos[i] = new MethodInfo(methods[i]);
246 }
247
248 int upcastCount = getAccessibleMethods(clazz, methodInfos, 0);
249
250 /*
251 * Reallocate array in case some method had no accessible counterpart.
252 */
253
254 if (upcastCount < methods.length) {
255 methods = new Method[upcastCount];
256 }
257
258 int j = 0;
259 for (MethodInfo methodInfo : methodInfos) {
260 if (methodInfo.upcast) {
261 methods[j++] = methodInfo.method;
262 }
263 }
264 return methods;
265 }
266
267 /**
268 * Recursively finds a match for each method, starting with the class, and then
269 * searching the superclass and interfaces.
270 *
271 * @param clazz Class to check
272 * @param methodInfos array of methods we are searching to match
273 * @param upcastCount current number of methods we have matched
274 * @return count of matched methods
275 */
276 private static int getAccessibleMethods(Class<?> clazz, MethodInfo[] methodInfos, int upcastCount) {
277 int l = methodInfos.length;
278
279 /*
280 * if this class is public, then check each of the currently
281 * 'non-upcasted' methods to see if we have a match
282 */
283
284 if (Modifier.isPublic(clazz.getModifiers())) {
285 for (int i = 0; i < l && upcastCount < l; ++i) {
286 try {
287 MethodInfo methodInfo = methodInfos[i];
288
289 if (!methodInfo.upcast) {
290 methodInfo.tryUpcasting(clazz);
291 upcastCount++;
292 }
293 } catch (NoSuchMethodException e) {
294 /*
295 * Intentionally ignored - it means
296 * it wasn't found in the current class
297 */
298 }
299 }
300
301 /*
302 * Short circuit if all methods were upcast
303 */
304
305 if (upcastCount == l) {
306 return upcastCount;
307 }
308 }
309
310 /*
311 * Examine superclass
312 */
313
314 Class<?> superclazz = clazz.getSuperclass();
315
316 if (superclazz != null) {
317 upcastCount = getAccessibleMethods(superclazz, methodInfos, upcastCount);
318
319 /*
320 * Short circuit if all methods were upcast
321 */
322
323 if (upcastCount == l) {
324 return upcastCount;
325 }
326 }
327
328 /*
329 * Examine interfaces. Note we do it even if superclazz == null.
330 * This is redundant as currently java.lang.Object does not implement
331 * any interfaces, however nothing guarantees it will not in future.
332 */
333
334 Class<?>[] interfaces = clazz.getInterfaces();
335
336 for (int i = interfaces.length; i-- > 0; ) {
337 upcastCount = getAccessibleMethods(interfaces[i], methodInfos, upcastCount);
338
339 /*
340 * Short circuit if all methods were upcast
341 */
342
343 if (upcastCount == l) {
344 return upcastCount;
345 }
346 }
347
348 return upcastCount;
349 }
350
351 /**
352 * For a given method, retrieves its publicly accessible counterpart.
353 * This method will look for a method with same name
354 * and signature declared in a public superclass or implemented interface of this
355 * method's declaring class. This counterpart method is publicly callable.
356 *
357 * @param method a method whose publicly callable counterpart is requested.
358 * @return the publicly callable counterpart method. Note that if the parameter
359 * method is itself declared by a public class, this method is an identity
360 * function.
361 */
362 public static Method getPublicMethod(Method method) {
363 Class<?> clazz = method.getDeclaringClass();
364
365 /*
366 * Short circuit for (hopefully the majority of) cases where the declaring
367 * class is public.
368 */
369
370 if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) {
371 return method;
372 }
373
374 return getPublicMethod(clazz, method.getName(), method.getParameterTypes());
375 }
376
377 /**
378 * Looks up the method with specified name and signature in the first public
379 * superclass or implemented interface of the class.
380 *
381 * @param class the class whose method is sought
382 * @param name the name of the method
383 * @param paramTypes the classes of method parameters
384 */
385 private static Method getPublicMethod(Class<?> clazz, String name, Class<?>[] paramTypes) {
386 /*
387 * if this class is public, then try to get it
388 */
389
390 if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) {
391 try {
392 return clazz.getMethod(name, paramTypes);
393 } catch (NoSuchMethodException e) {
394 /*
395 * If the class does not have the method, then neither its
396 * superclass nor any of its interfaces has it so quickly return
397 * null.
398 */
399 return null;
400 }
401 }
402
403 /*
404 * try the superclass
405 */
406
407 Class<?> superclazz = clazz.getSuperclass();
408
409 if (superclazz != null) {
410 Method superclazzMethod = getPublicMethod(superclazz, name, paramTypes);
411
412 if (superclazzMethod != null) {
413 return superclazzMethod;
414 }
415 }
416
417 /*
418 * and interfaces
419 */
420
421 for (Class<?> interface_ : clazz.getInterfaces()) {
422 Method interfaceMethod = getPublicMethod(interface_, name, paramTypes);
423
424 if (interfaceMethod != null) {
425 return interfaceMethod;
426 }
427 }
428
429 return null;
430 }
431
432 /**
433 * Used for the iterative discovery process for public methods.
434 */
435 private static final class MethodInfo {
436 Method method;
437 String name;
438 Class<?>[] parameterTypes;
439 boolean upcast;
440
441 MethodInfo(Method method) {
442 this.method = null;
443 name = method.getName();
444 parameterTypes = method.getParameterTypes();
445 upcast = false;
446 }
447
448 void tryUpcasting(Class<?> clazz) throws NoSuchMethodException {
449 method = clazz.getMethod(name, parameterTypes);
450 name = null;
451 parameterTypes = null;
452 upcast = true;
453 }
454 }
455 }