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