Coverage Report - org.apache.commons.lang3.reflect.MemberUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
MemberUtils
95%
42/44
84%
39/46
4,571
 
 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  0
 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  1
     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  285
         if (o == null || o.isAccessible()) {
 55  72
             return false;
 56  
         }
 57  213
         final Member m = (Member) o;
 58  213
         if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) {
 59  
             try {
 60  14
                 o.setAccessible(true);
 61  14
                 return true;
 62  0
             } catch (final SecurityException e) { // NOPMD
 63  
                 // ignore in favor of subsequent IllegalAccessException
 64  
             }
 65  
         }
 66  199
         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  204
         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  226
         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  51
         final float leftCost = getTotalTransformationCost(actual, left);
 101  51
         final float rightCost = getTotalTransformationCost(actual, right);
 102  51
         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  102
         float totalCost = 0.0f;
 114  204
         for (int i = 0; i < srcArgs.length; i++) {
 115  
             Class<?> srcClass, destClass;
 116  102
             srcClass = srcArgs[i];
 117  102
             destClass = destArgs[i];
 118  102
             totalCost += getObjectTransformationCost(srcClass, destClass);
 119  
         }
 120  102
         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  102
         if (destClass.isPrimitive()) {
 133  61
             return getPrimitivePromotionCost(srcClass, destClass);
 134  
         }
 135  41
         float cost = 0.0f;
 136  106
         while (srcClass != null && !destClass.equals(srcClass)) {
 137  67
             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  2
                 cost += 0.25f;
 144  2
                 break;
 145  
             }
 146  65
             cost++;
 147  65
             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  41
         if (srcClass == null) {
 154  10
             cost += 1.5f;
 155  
         }
 156  41
         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  61
         float cost = 0.0f;
 168  61
         Class<?> cls = srcClass;
 169  61
         if (!cls.isPrimitive()) {
 170  
             // slight unwrapping penalty
 171  39
             cost += 0.1f;
 172  39
             cls = ClassUtils.wrapperToPrimitive(cls);
 173  
         }
 174  349
         for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
 175  288
             if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
 176  204
                 cost += 0.1f;
 177  204
                 if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
 178  204
                     cls = ORDERED_PRIMITIVE_TYPES[i + 1];
 179  
                 }
 180  
             }
 181  
         }
 182  61
         return cost;
 183  
     }
 184  
 
 185  
 }