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   * @version $Id: MemberUtils.java 1563993 2014-02-03 18:45:16Z ggregory $
31   */
32  abstract class MemberUtils {
33      // TODO extract an interface to implement compareParameterSets(...)?
34  
35      private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;
36  
37      /** Array of primitive number types ordered by "promotability" */
38      private static final Class<?>[] ORDERED_PRIMITIVE_TYPES = { Byte.TYPE, Short.TYPE,
39              Character.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE };
40  
41      /**
42       * XXX Default access superclass workaround.
43       *
44       * When a {@code public} class has a default access superclass with {@code public} members,
45       * these members are accessible. Calling them from compiled code works fine.
46       * Unfortunately, on some JVMs, using reflection to invoke these members
47       * seems to (wrongly) prevent access even when the modifier is {@code public}.
48       * Calling {@code setAccessible(true)} solves the problem but will only work from
49       * sufficiently privileged code. Better workarounds would be gratefully
50       * accepted.
51       * @param o the AccessibleObject to set as accessible
52       * @return a boolean indicating whether the accessibility of the object was set to true.
53       */
54      static boolean setAccessibleWorkaround(final AccessibleObject o) {
55          if (o == null || o.isAccessible()) {
56              return false;
57          }
58          final Member m = (Member) o;
59          if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) {
60              try {
61                  o.setAccessible(true);
62                  return true;
63              } catch (final SecurityException e) { // NOPMD
64                  // ignore in favor of subsequent IllegalAccessException
65              }
66          }
67          return false;
68      }
69  
70      /**
71       * Returns whether a given set of modifiers implies package access.
72       * @param modifiers to test
73       * @return {@code true} unless {@code package}/{@code protected}/{@code private} modifier detected
74       */
75      static boolean isPackageAccess(final int modifiers) {
76          return (modifiers & ACCESS_TEST) == 0;
77      }
78  
79      /**
80       * Returns whether a {@link Member} is accessible.
81       * @param m Member to check
82       * @return {@code true} if <code>m</code> is accessible
83       */
84      static boolean isAccessible(final Member m) {
85          return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic();
86      }
87  
88      /**
89       * Compares the relative fitness of two sets of parameter types in terms of
90       * matching a third set of runtime parameter types, such that a list ordered
91       * by the results of the comparison would return the best match first
92       * (least).
93       *
94       * @param left the "left" parameter set
95       * @param right the "right" parameter set
96       * @param actual the runtime parameter types to match against
97       * {@code left}/{@code right}
98       * @return int consistent with {@code compare} semantics
99       */
100     static int compareParameterTypes(final Class<?>[] left, final Class<?>[] right, final Class<?>[] actual) {
101         final float leftCost = getTotalTransformationCost(actual, left);
102         final float rightCost = getTotalTransformationCost(actual, right);
103         return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0;
104     }
105 
106     /**
107      * Returns the sum of the object transformation cost for each class in the
108      * source argument list.
109      * @param srcArgs The source arguments
110      * @param destArgs The destination arguments
111      * @return The total transformation cost
112      */
113     private static float getTotalTransformationCost(final Class<?>[] srcArgs, final Class<?>[] destArgs) {
114         float totalCost = 0.0f;
115         for (int i = 0; i < srcArgs.length; i++) {
116             Class<?> srcClass, destClass;
117             srcClass = srcArgs[i];
118             destClass = destArgs[i];
119             totalCost += getObjectTransformationCost(srcClass, destClass);
120         }
121         return totalCost;
122     }
123 
124     /**
125      * Gets the number of steps required needed to turn the source class into
126      * the destination class. This represents the number of steps in the object
127      * hierarchy graph.
128      * @param srcClass The source class
129      * @param destClass The destination class
130      * @return The cost of transforming an object
131      */
132     private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) {
133         if (destClass.isPrimitive()) {
134             return getPrimitivePromotionCost(srcClass, destClass);
135         }
136         float cost = 0.0f;
137         while (srcClass != null && !destClass.equals(srcClass)) {
138             if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
139                 // slight penalty for interface match.
140                 // we still want an exact match to override an interface match,
141                 // but
142                 // an interface match should override anything where we have to
143                 // get a superclass.
144                 cost += 0.25f;
145                 break;
146             }
147             cost++;
148             srcClass = srcClass.getSuperclass();
149         }
150         /*
151          * If the destination class is null, we've travelled all the way up to
152          * an Object match. We'll penalize this by adding 1.5 to the cost.
153          */
154         if (srcClass == null) {
155             cost += 1.5f;
156         }
157         return cost;
158     }
159 
160     /**
161      * Gets the number of steps required to promote a primitive number to another
162      * type.
163      * @param srcClass the (primitive) source class
164      * @param destClass the (primitive) destination class
165      * @return The cost of promoting the primitive
166      */
167     private static float getPrimitivePromotionCost(final Class<?> srcClass, final Class<?> destClass) {
168         float cost = 0.0f;
169         Class<?> cls = srcClass;
170         if (!cls.isPrimitive()) {
171             // slight unwrapping penalty
172             cost += 0.1f;
173             cls = ClassUtils.wrapperToPrimitive(cls);
174         }
175         for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
176             if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
177                 cost += 0.1f;
178                 if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
179                     cls = ORDERED_PRIMITIVE_TYPES[i + 1];
180                 }
181             }
182         }
183         return cost;
184     }
185 
186 }