Coverage Report - org.apache.commons.lang3.reflect.ConstructorUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
ConstructorUtils
93%
45/48
81%
18/22
3
 
 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.Constructor;
 20  
 import java.lang.reflect.InvocationTargetException;
 21  
 import java.lang.reflect.Modifier;
 22  
 
 23  
 import org.apache.commons.lang3.ArrayUtils;
 24  
 import org.apache.commons.lang3.ClassUtils;
 25  
 import org.apache.commons.lang3.Validate;
 26  
 
 27  
 /**
 28  
  * <p> Utility reflection methods focused on constructors, modeled after
 29  
  * {@link MethodUtils}. </p>
 30  
  *
 31  
  * <h3>Known Limitations</h3> <h4>Accessing Public Constructors In A Default
 32  
  * Access Superclass</h4> <p>There is an issue when invoking {@code public} constructors
 33  
  * contained in a default access superclass. Reflection correctly locates these
 34  
  * constructors and assigns them as {@code public}. However, an
 35  
  * {@link IllegalAccessException} is thrown if the constructor is
 36  
  * invoked.</p>
 37  
  *
 38  
  * <p>{@link ConstructorUtils} contains a workaround for this situation: it
 39  
  * will attempt to call {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} on this constructor. If this
 40  
  * call succeeds, then the method can be invoked as normal. This call will only
 41  
  * succeed when the application has sufficient security privileges. If this call
 42  
  * fails then a warning will be logged and the method may fail.</p>
 43  
  *
 44  
  * @since 2.5
 45  
  */
 46  
 public class ConstructorUtils {
 47  
 
 48  
     /**
 49  
      * <p>ConstructorUtils instances should NOT be constructed in standard
 50  
      * programming. Instead, the class should be used as
 51  
      * {@code ConstructorUtils.invokeConstructor(cls, args)}.</p>
 52  
      *
 53  
      * <p>This constructor is {@code public} to permit tools that require a JavaBean
 54  
      * instance to operate.</p>
 55  
      */
 56  
     public ConstructorUtils() {
 57  0
         super();
 58  0
     }
 59  
 
 60  
     /**
 61  
      * <p>Returns a new instance of the specified class inferring the right constructor
 62  
      * from the types of the arguments.</p>
 63  
      * 
 64  
      * <p>This locates and calls a constructor.
 65  
      * The constructor signature must match the argument types by assignment compatibility.</p>
 66  
      *
 67  
      * @param <T> the type to be constructed
 68  
      * @param cls  the class to be constructed, not {@code null}
 69  
      * @param args  the array of arguments, {@code null} treated as empty
 70  
      * @return new instance of {@code cls}, not {@code null}
 71  
      *
 72  
      * @throws NullPointerException if {@code cls} is {@code null}
 73  
      * @throws NoSuchMethodException if a matching constructor cannot be found
 74  
      * @throws IllegalAccessException if invocation is not permitted by security
 75  
      * @throws InvocationTargetException if an error occurs on invocation
 76  
      * @throws InstantiationException if an error occurs on instantiation
 77  
      * @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
 78  
      */
 79  
     public static <T> T invokeConstructor(final Class<T> cls, Object... args)
 80  
             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
 81  
             InstantiationException {
 82  10
         args = ArrayUtils.nullToEmpty(args);
 83  10
         final Class<?> parameterTypes[] = ClassUtils.toClass(args);
 84  10
         return invokeConstructor(cls, args, parameterTypes);
 85  
     }
 86  
 
 87  
     /**
 88  
      * <p>Returns a new instance of the specified class choosing the right constructor
 89  
      * from the list of parameter types.</p>
 90  
      * 
 91  
      * <p>This locates and calls a constructor.
 92  
      * The constructor signature must match the parameter types by assignment compatibility.</p>
 93  
      *
 94  
      * @param <T> the type to be constructed
 95  
      * @param cls  the class to be constructed, not {@code null}
 96  
      * @param args  the array of arguments, {@code null} treated as empty
 97  
      * @param parameterTypes  the array of parameter types, {@code null} treated as empty
 98  
      * @return new instance of {@code cls}, not {@code null}
 99  
      *
 100  
      * @throws NullPointerException if {@code cls} is {@code null}
 101  
      * @throws NoSuchMethodException if a matching constructor cannot be found
 102  
      * @throws IllegalAccessException if invocation is not permitted by security
 103  
      * @throws InvocationTargetException if an error occurs on invocation
 104  
      * @throws InstantiationException if an error occurs on instantiation
 105  
      * @see Constructor#newInstance
 106  
      */
 107  
     public static <T> T invokeConstructor(final Class<T> cls, Object[] args, Class<?>[] parameterTypes)
 108  
             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
 109  
             InstantiationException {
 110  10
         args = ArrayUtils.nullToEmpty(args);
 111  10
         parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
 112  10
         final Constructor<T> ctor = getMatchingAccessibleConstructor(cls, parameterTypes);
 113  10
         if (ctor == null) {
 114  0
             throw new NoSuchMethodException(
 115  
                 "No such accessible constructor on object: " + cls.getName());
 116  
         }
 117  10
         return ctor.newInstance(args);
 118  
     }
 119  
 
 120  
     /**
 121  
      * <p>Returns a new instance of the specified class inferring the right constructor
 122  
      * from the types of the arguments.</p>
 123  
      *
 124  
      * <p>This locates and calls a constructor.
 125  
      * The constructor signature must match the argument types exactly.</p>
 126  
      *
 127  
      * @param <T> the type to be constructed
 128  
      * @param cls the class to be constructed, not {@code null}
 129  
      * @param args the array of arguments, {@code null} treated as empty
 130  
      * @return new instance of {@code cls}, not {@code null}
 131  
      *
 132  
      * @throws NullPointerException if {@code cls} is {@code null}
 133  
      * @throws NoSuchMethodException if a matching constructor cannot be found
 134  
      * @throws IllegalAccessException if invocation is not permitted by security
 135  
      * @throws InvocationTargetException if an error occurs on invocation
 136  
      * @throws InstantiationException if an error occurs on instantiation
 137  
      * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
 138  
      */
 139  
     public static <T> T invokeExactConstructor(final Class<T> cls, Object... args)
 140  
             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
 141  
             InstantiationException {
 142  8
         args = ArrayUtils.nullToEmpty(args);
 143  8
         final Class<?> parameterTypes[] = ClassUtils.toClass(args);
 144  8
         return invokeExactConstructor(cls, args, parameterTypes);
 145  
     }
 146  
 
 147  
     /**
 148  
      * <p>Returns a new instance of the specified class choosing the right constructor
 149  
      * from the list of parameter types.</p>
 150  
      *
 151  
      * <p>This locates and calls a constructor.
 152  
      * The constructor signature must match the parameter types exactly.</p>
 153  
      *
 154  
      * @param <T> the type to be constructed
 155  
      * @param cls the class to be constructed, not {@code null}
 156  
      * @param args the array of arguments, {@code null} treated as empty
 157  
      * @param parameterTypes  the array of parameter types, {@code null} treated as empty
 158  
      * @return new instance of <code>cls</code>, not {@code null}
 159  
      *
 160  
      * @throws NullPointerException if {@code cls} is {@code null}
 161  
      * @throws NoSuchMethodException if a matching constructor cannot be found
 162  
      * @throws IllegalAccessException if invocation is not permitted by security
 163  
      * @throws InvocationTargetException if an error occurs on invocation
 164  
      * @throws InstantiationException if an error occurs on instantiation
 165  
      * @see Constructor#newInstance
 166  
      */
 167  
     public static <T> T invokeExactConstructor(final Class<T> cls, Object[] args,
 168  
             Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException,
 169  
             InvocationTargetException, InstantiationException {
 170  9
         args = ArrayUtils.nullToEmpty(args);
 171  9
         parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
 172  9
         final Constructor<T> ctor = getAccessibleConstructor(cls, parameterTypes);
 173  9
         if (ctor == null) {
 174  3
             throw new NoSuchMethodException(
 175  
                 "No such accessible constructor on object: "+ cls.getName());
 176  
         }
 177  6
         return ctor.newInstance(args);
 178  
     }
 179  
 
 180  
     //-----------------------------------------------------------------------
 181  
     /**
 182  
      * <p>Finds a constructor given a class and signature, checking accessibility.</p>
 183  
      * 
 184  
      * <p>This finds the constructor and ensures that it is accessible.
 185  
      * The constructor signature must match the parameter types exactly.</p>
 186  
      *
 187  
      * @param <T> the constructor type
 188  
      * @param cls the class to find a constructor for, not {@code null}
 189  
      * @param parameterTypes the array of parameter types, {@code null} treated as empty
 190  
      * @return the constructor, {@code null} if no matching accessible constructor found
 191  
      * @see Class#getConstructor
 192  
      * @see #getAccessibleConstructor(java.lang.reflect.Constructor)
 193  
      * @throws NullPointerException if {@code cls} is {@code null}
 194  
      */
 195  
     public static <T> Constructor<T> getAccessibleConstructor(final Class<T> cls,
 196  
             final Class<?>... parameterTypes) {
 197  12
         Validate.notNull(cls, "class cannot be null");
 198  
         try {
 199  12
             return getAccessibleConstructor(cls.getConstructor(parameterTypes));
 200  3
         } catch (final NoSuchMethodException e) {
 201  3
             return null;
 202  
         }
 203  
     }
 204  
 
 205  
     /**
 206  
      * <p>Checks if the specified constructor is accessible.</p>
 207  
      * 
 208  
      * <p>This simply ensures that the constructor is accessible.</p>
 209  
      *
 210  
      * @param <T> the constructor type
 211  
      * @param ctor  the prototype constructor object, not {@code null}
 212  
      * @return the constructor, {@code null} if no matching accessible constructor found
 213  
      * @see java.lang.SecurityManager
 214  
      * @throws NullPointerException if {@code ctor} is {@code null}
 215  
      */
 216  
     public static <T> Constructor<T> getAccessibleConstructor(final Constructor<T> ctor) {
 217  49
         Validate.notNull(ctor, "constructor cannot be null");
 218  49
         return MemberUtils.isAccessible(ctor)
 219  
                 && isAccessible(ctor.getDeclaringClass()) ? ctor : null;
 220  
     }
 221  
 
 222  
     /**
 223  
      * <p>Finds an accessible constructor with compatible parameters.</p>
 224  
      * 
 225  
      * <p>This checks all the constructor and finds one with compatible parameters
 226  
      * This requires that every parameter is assignable from the given parameter types.
 227  
      * This is a more flexible search than the normal exact matching algorithm.</p>
 228  
      *
 229  
      * <p>First it checks if there is a constructor matching the exact signature.
 230  
      * If not then all the constructors of the class are checked to see if their
 231  
      * signatures are assignment-compatible with the parameter types.
 232  
      * The first assignment-compatible matching constructor is returned.</p>
 233  
      *
 234  
      * @param <T> the constructor type
 235  
      * @param cls  the class to find a constructor for, not {@code null}
 236  
      * @param parameterTypes find method with compatible parameters
 237  
      * @return the constructor, null if no matching accessible constructor found
 238  
      * @throws NullPointerException if {@code cls} is {@code null}
 239  
      */
 240  
     public static <T> Constructor<T> getMatchingAccessibleConstructor(final Class<T> cls,
 241  
             final Class<?>... parameterTypes) {
 242  30
         Validate.notNull(cls, "class cannot be null");
 243  
         // see if we can find the constructor directly
 244  
         // most of the time this works and it's much faster
 245  
         try {
 246  30
             final Constructor<T> ctor = cls.getConstructor(parameterTypes);
 247  13
             MemberUtils.setAccessibleWorkaround(ctor);
 248  13
             return ctor;
 249  17
         } catch (final NoSuchMethodException e) { // NOPMD - Swallow
 250  
         }
 251  17
         Constructor<T> result = null;
 252  
         /*
 253  
          * (1) Class.getConstructors() is documented to return Constructor<T> so as
 254  
          * long as the array is not subsequently modified, everything's fine.
 255  
          */
 256  17
         final Constructor<?>[] ctors = cls.getConstructors();
 257  
 
 258  
         // return best match:
 259  115
         for (Constructor<?> ctor : ctors) {
 260  
             // compare parameters
 261  98
             if (ClassUtils.isAssignable(parameterTypes, ctor.getParameterTypes(), true)) {
 262  
                 // get accessible version of constructor
 263  38
                 ctor = getAccessibleConstructor(ctor);
 264  38
                 if (ctor != null) {
 265  38
                     MemberUtils.setAccessibleWorkaround(ctor);
 266  38
                     if (result == null
 267  
                             || MemberUtils.compareParameterTypes(ctor.getParameterTypes(), result
 268  
                                     .getParameterTypes(), parameterTypes) < 0) {
 269  
                         // temporary variable for annotation, see comment above (1)
 270  
                         @SuppressWarnings("unchecked")
 271  
                         final
 272  38
                         Constructor<T> constructor = (Constructor<T>)ctor;
 273  38
                         result = constructor;
 274  
                     }
 275  
                 }
 276  
             }
 277  
         }
 278  17
         return result;
 279  
     }
 280  
 
 281  
     /**
 282  
      * Learn whether the specified class is generally accessible, i.e. is
 283  
      * declared in an entirely {@code public} manner.
 284  
      * @param type to check
 285  
      * @return {@code true} if {@code type} and any enclosing classes are
 286  
      *         {@code public}.
 287  
      */
 288  
     private static boolean isAccessible(final Class<?> type) {
 289  49
         Class<?> cls = type;
 290  139
         while (cls != null) {
 291  93
             if (!Modifier.isPublic(cls.getModifiers())) {
 292  3
                 return false;
 293  
             }
 294  90
             cls = cls.getEnclosingClass();
 295  
         }
 296  46
         return true;
 297  
     }
 298  
 
 299  
 }