001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3.reflect;
018
019import java.lang.reflect.Constructor;
020import java.lang.reflect.InvocationTargetException;
021import java.lang.reflect.Modifier;
022
023import org.apache.commons.lang3.ArrayUtils;
024import org.apache.commons.lang3.ClassUtils;
025import org.apache.commons.lang3.Validate;
026
027/**
028 * <p> Utility reflection methods focused on constructors, modeled after
029 * {@link MethodUtils}. </p>
030 *
031 * <h3>Known Limitations</h3> <h4>Accessing Public Constructors In A Default
032 * Access Superclass</h4> <p>There is an issue when invoking {@code public} constructors
033 * contained in a default access superclass. Reflection correctly locates these
034 * constructors and assigns them as {@code public}. However, an
035 * {@link IllegalAccessException} is thrown if the constructor is
036 * invoked.</p>
037 *
038 * <p>{@link ConstructorUtils} contains a workaround for this situation: it
039 * will attempt to call {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} on this constructor. If this
040 * call succeeds, then the method can be invoked as normal. This call will only
041 * succeed when the application has sufficient security privileges. If this call
042 * fails then a warning will be logged and the method may fail.</p>
043 *
044 * @since 2.5
045 * @version $Id: ConstructorUtils.java 1534831 2013-10-22 22:41:06Z mbenson $
046 */
047public class ConstructorUtils {
048
049    /**
050     * <p>ConstructorUtils instances should NOT be constructed in standard
051     * programming. Instead, the class should be used as
052     * {@code ConstructorUtils.invokeConstructor(cls, args)}.</p>
053     *
054     * <p>This constructor is {@code public} to permit tools that require a JavaBean
055     * instance to operate.</p>
056     */
057    public ConstructorUtils() {
058        super();
059    }
060
061    /**
062     * <p>Returns a new instance of the specified class inferring the right constructor
063     * from the types of the arguments.</p>
064     * 
065     * <p>This locates and calls a constructor.
066     * The constructor signature must match the argument types by assignment compatibility.</p>
067     *
068     * @param <T> the type to be constructed
069     * @param cls  the class to be constructed, not {@code null}
070     * @param args  the array of arguments, {@code null} treated as empty
071     * @return new instance of {@code cls}, not {@code null}
072     *
073     * @throws NullPointerException if {@code cls} is {@code null}
074     * @throws NoSuchMethodException if a matching constructor cannot be found
075     * @throws IllegalAccessException if invocation is not permitted by security
076     * @throws InvocationTargetException if an error occurs on invocation
077     * @throws InstantiationException if an error occurs on instantiation
078     * @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[])
079     */
080    public static <T> T invokeConstructor(final Class<T> cls, Object... args)
081            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
082            InstantiationException {
083        args = ArrayUtils.nullToEmpty(args);
084        final Class<?> parameterTypes[] = ClassUtils.toClass(args);
085        return invokeConstructor(cls, args, parameterTypes);
086    }
087
088    /**
089     * <p>Returns a new instance of the specified class choosing the right constructor
090     * from the list of parameter types.</p>
091     * 
092     * <p>This locates and calls a constructor.
093     * The constructor signature must match the parameter types by assignment compatibility.</p>
094     *
095     * @param <T> the type to be constructed
096     * @param cls  the class to be constructed, not {@code null}
097     * @param args  the array of arguments, {@code null} treated as empty
098     * @param parameterTypes  the array of parameter types, {@code null} treated as empty
099     * @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                && Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) ? 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}