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