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