View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.reflect;
18  
19  import java.lang.reflect.AccessibleObject;
20  import java.lang.reflect.Member;
21  import java.lang.reflect.Modifier;
22  
23  import org.apache.commons.lang3.ClassUtils;
24  
25  /**
26   * Contains common code for working with {@link java.lang.reflect.Method Methods}/{@link java.lang.reflect.Constructor Constructors},
27   * extracted and refactored from {@link MethodUtils} when it was imported from Commons BeanUtils.
28   *
29   * @since 2.5
30   */
31  abstract class MemberUtils {
32      // TODO extract an interface to implement compareParameterSets(...)?
33  
34      private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;
35  
36      /** Array of primitive number types ordered by "promotability" */
37      private static final Class<?>[] ORDERED_PRIMITIVE_TYPES = { Byte.TYPE, Short.TYPE,
38              Character.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE };
39  
40      /**
41       * XXX Default access superclass workaround.
42       *
43       * When a {@code public} class has a default access superclass with {@code public} members,
44       * these members are accessible. Calling them from compiled code works fine.
45       * Unfortunately, on some JVMs, using reflection to invoke these members
46       * seems to (wrongly) prevent access even when the modifier is {@code public}.
47       * Calling {@code setAccessible(true)} solves the problem but will only work from
48       * sufficiently privileged code. Better workarounds would be gratefully
49       * accepted.
50       * @param o the AccessibleObject to set as accessible
51       * @return a boolean indicating whether the accessibility of the object was set to true.
52       */
53      static boolean setAccessibleWorkaround(final AccessibleObject o) {
54          if (o == null || o.isAccessible()) {
55              return false;
56          }
57          final Member m = (Member) o;
58          if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) {
59              try {
60                  o.setAccessible(true);
61                  return true;
62              } catch (final SecurityException e) { // NOPMD
63                  // ignore in favor of subsequent IllegalAccessException
64              }
65          }
66          return false;
67      }
68  
69      /**
70       * Returns whether a given set of modifiers implies package access.
71       * @param modifiers to test
72       * @return {@code true} unless {@code package}/{@code protected}/{@code private} modifier detected
73       */
74      static boolean isPackageAccess(final int modifiers) {
75          return (modifiers & ACCESS_TEST) == 0;
76      }
77  
78      /**
79       * Returns whether a {@link Member} is accessible.
80       * @param m Member to check
81       * @return {@code true} if <code>m</code> is accessible
82       */
83      static boolean isAccessible(final Member m) {
84          return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic();
85      }
86  
87      /**
88       * Compares the relative fitness of two sets of parameter types in terms of
89       * matching a third set of runtime parameter types, such that a list ordered
90       * by the results of the comparison would return the best match first
91       * (least).
92       *
93       * @param left the "left" parameter set
94       * @param right the "right" parameter set
95       * @param actual the runtime parameter types to match against
96       * {@code left}/{@code right}
97       * @return int consistent with {@code compare} semantics
98       */
99      static int compareParameterTypes(final Class<?>[] left, final Class<?>[] right, final Class<?>[] actual) {
100         final float leftCost = getTotalTransformationCost(actual, left);
101         final float rightCost = getTotalTransformationCost(actual, right);
102         return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0;
103     }
104 
105     /**
106      * Returns the sum of the object transformation cost for each class in the
107      * source argument list.
108      * @param srcArgs The source arguments
109      * @param destArgs The destination arguments
110      * @return The total transformation cost
111      */
112     private static float getTotalTransformationCost(final Class<?>[] srcArgs, final Class<?>[] destArgs) {
113         float totalCost = 0.0f;
114         for (int i = 0; i < srcArgs.length; i++) {
115             Class<?> srcClass, destClass;
116             srcClass = srcArgs[i];
117             destClass = destArgs[i];
118             totalCost += getObjectTransformationCost(srcClass, destClass);
119         }
120         return totalCost;
121     }
122 
123     /**
124      * Gets the number of steps required needed to turn the source class into
125      * the destination class. This represents the number of steps in the object
126      * hierarchy graph.
127      * @param srcClass The source class
128      * @param destClass The destination class
129      * @return The cost of transforming an object
130      */
131     private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) {
132         if (destClass.isPrimitive()) {
133             return getPrimitivePromotionCost(srcClass, destClass);
134         }
135         float cost = 0.0f;
136         while (srcClass != null && !destClass.equals(srcClass)) {
137             if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
138                 // slight penalty for interface match.
139                 // we still want an exact match to override an interface match,
140                 // but
141                 // an interface match should override anything where we have to
142                 // get a superclass.
143                 cost += 0.25f;
144                 break;
145             }
146             cost++;
147             srcClass = srcClass.getSuperclass();
148         }
149         /*
150          * If the destination class is null, we've travelled all the way up to
151          * an Object match. We'll penalize this by adding 1.5 to the cost.
152          */
153         if (srcClass == null) {
154             cost += 1.5f;
155         }
156         return cost;
157     }
158 
159     /**
160      * Gets the number of steps required to promote a primitive number to another
161      * type.
162      * @param srcClass the (primitive) source class
163      * @param destClass the (primitive) destination class
164      * @return The cost of promoting the primitive
165      */
166     private static float getPrimitivePromotionCost(final Class<?> srcClass, final Class<?> destClass) {
167         float cost = 0.0f;
168         Class<?> cls = srcClass;
169         if (!cls.isPrimitive()) {
170             // slight unwrapping penalty
171             cost += 0.1f;
172             cls = ClassUtils.wrapperToPrimitive(cls);
173         }
174         for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
175             if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
176                 cost += 0.1f;
177                 if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
178                     cls = ORDERED_PRIMITIVE_TYPES[i + 1];
179                 }
180             }
181         }
182         return cost;
183     }
184 
185 }