ConstructorUtils.java

  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.beanutils2;

  18. import java.lang.reflect.Array;
  19. import java.lang.reflect.Constructor;
  20. import java.lang.reflect.InvocationTargetException;
  21. import java.lang.reflect.Modifier;

  22. /**
  23.  * <p>
  24.  * Utility reflection methods focused on constructors, modeled after {@link MethodUtils}.
  25.  * </p>
  26.  *
  27.  * <h2>Known Limitations</h2>
  28.  * <h3>Accessing Public Constructors In A Default Access Superclass</h3>
  29.  * <p>
  30.  * There is an issue when invoking public constructors contained in a default access superclass. Reflection locates these constructors fine and correctly
  31.  * assigns them as public. However, an {@code IllegalAccessException} is thrown if the constructors is invoked.
  32.  * </p>
  33.  *
  34.  * <p>
  35.  * {@code ConstructorUtils} contains a workaround for this situation. It will attempt to call {@code setAccessible} on this constructor. If this call succeeds,
  36.  * then the method can be invoked as normal. This call will only succeed when the application has sufficient security privileges. If this call fails then a
  37.  * warning will be logged and the method may fail.
  38.  * </p>
  39.  */
  40. public final class ConstructorUtils {

  41.     /**
  42.      * Returns a constructor with single argument.
  43.      *
  44.      * @param <T>           the type of the constructor
  45.      * @param klass         the class to be constructed
  46.      * @param parameterType The constructor parameter type
  47.      * @return null if matching accessible constructor cannot be found.
  48.      * @see Class#getConstructor
  49.      * @see #getAccessibleConstructor(java.lang.reflect.Constructor)
  50.      */
  51.     public static <T> Constructor<T> getAccessibleConstructor(final Class<T> klass, final Class<?> parameterType) {

  52.         final Class<?>[] parameterTypes = { parameterType };
  53.         return getAccessibleConstructor(klass, parameterTypes);
  54.     }

  55.     /**
  56.      * Returns a constructor given a class and signature.
  57.      *
  58.      * @param <T>            the type to be constructed
  59.      * @param klass          the class to be constructed
  60.      * @param parameterTypes the parameter array
  61.      * @return null if matching accessible constructor cannot be found
  62.      * @see Class#getConstructor
  63.      * @see #getAccessibleConstructor(java.lang.reflect.Constructor)
  64.      */
  65.     public static <T> Constructor<T> getAccessibleConstructor(final Class<T> klass, final Class<?>[] parameterTypes) {

  66.         try {
  67.             return getAccessibleConstructor(klass.getConstructor(parameterTypes));
  68.         } catch (final NoSuchMethodException e) {
  69.             return null;
  70.         }
  71.     }

  72.     /**
  73.      * Returns accessible version of the given constructor.
  74.      *
  75.      * @param <T>  the type of the constructor
  76.      * @param ctor prototype constructor object.
  77.      * @return {@code null} if accessible constructor cannot be found.
  78.      * @see SecurityManager
  79.      */
  80.     public static <T> Constructor<T> getAccessibleConstructor(final Constructor<T> ctor) {

  81.         // Make sure we have a method to check
  82.         if (ctor == null) {
  83.             return null;
  84.         }

  85.         // If the requested method is not public we cannot call it
  86.         if (!Modifier.isPublic(ctor.getModifiers())) {
  87.             return null;
  88.         }

  89.         // If the declaring class is public, we are done
  90.         final Class<T> clazz = ctor.getDeclaringClass();
  91.         if (Modifier.isPublic(clazz.getModifiers())) {
  92.             return ctor;
  93.         }

  94.         // what else can we do?
  95.         return null;
  96.     }

  97.     /**
  98.      * <p>
  99.      * Find an accessible constructor with compatible parameters. Compatible parameters mean that every method parameter is assignable from the given
  100.      * parameters. In other words, it finds constructor that will take the parameters given.
  101.      * </p>
  102.      *
  103.      * <p>
  104.      * First it checks if there is constructor matching the exact signature. If no such, all the constructors of the class are tested if their signatures are
  105.      * assignment compatible with the parameter types. The first matching constructor is returned.
  106.      * </p>
  107.      *
  108.      * @param <T>            the type of the class to be inspected
  109.      * @param clazz          find constructor for this class
  110.      * @param parameterTypes find method with compatible parameters
  111.      * @return a valid Constructor object. If there's no matching constructor, returns {@code null}.
  112.      */
  113.     private static <T> Constructor<T> getMatchingAccessibleConstructor(final Class<T> clazz, final Class<?>[] parameterTypes) {
  114.         // see if we can find the method directly
  115.         // most of the time this works and it's much faster
  116.         try {
  117.             final Constructor<T> ctor = clazz.getConstructor(parameterTypes);
  118.             try {
  119.                 //
  120.                 // XXX Default access superclass workaround
  121.                 //
  122.                 // When a public class has a default access superclass
  123.                 // with public methods, these methods are accessible.
  124.                 // Calling them from compiled code works fine.
  125.                 //
  126.                 // Unfortunately, using reflection to invoke these methods
  127.                 // seems to (wrongly) to prevent access even when the method
  128.                 // modifier is public.
  129.                 //
  130.                 // The following workaround solves the problem but will only
  131.                 // work from sufficiently privileges code.
  132.                 //
  133.                 // Better workarounds would be gratefully accepted.
  134.                 //
  135.                 ctor.setAccessible(true);
  136.             } catch (final SecurityException se) {
  137.                 /* SWALLOW, if workaround fails don't fret. */
  138.             }
  139.             return ctor;

  140.         } catch (final NoSuchMethodException e) { /* SWALLOW */
  141.         }

  142.         // search through all methods
  143.         final int paramSize = parameterTypes.length;
  144.         final Constructor<?>[] ctors = clazz.getConstructors();
  145.         for (final Constructor<?> ctor2 : ctors) {
  146.             // compare parameters
  147.             final Class<?>[] ctorParams = ctor2.getParameterTypes();
  148.             final int ctorParamSize = ctorParams.length;
  149.             if (ctorParamSize == paramSize) {
  150.                 boolean match = true;
  151.                 for (int n = 0; n < ctorParamSize; n++) {
  152.                     if (!MethodUtils.isAssignmentCompatible(ctorParams[n], parameterTypes[n])) {
  153.                         match = false;
  154.                         break;
  155.                     }
  156.                 }

  157.                 if (match) {
  158.                     // get accessible version of method
  159.                     final Constructor<?> ctor = getAccessibleConstructor(ctor2);
  160.                     if (ctor != null) {
  161.                         try {
  162.                             ctor.setAccessible(true);
  163.                         } catch (final SecurityException se) {
  164.                             /*
  165.                              * Swallow SecurityException TODO: Why?
  166.                              */
  167.                         }
  168.                         // Class.getConstructors() actually returns constructors
  169.                         // of type T, so it is safe to cast.
  170.                         return (Constructor<T>) ctor;
  171.                     }
  172.                 }
  173.             }
  174.         }

  175.         return null;
  176.     }

  177.     /**
  178.      * <p>
  179.      * Convenience method returning new instance of {@code klazz} using a single argument constructor. The formal parameter type is inferred from the actual
  180.      * values of {@code arg}. See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.
  181.      * </p>
  182.      *
  183.      * <p>
  184.      * The signatures should be assignment compatible.
  185.      * </p>
  186.      *
  187.      * @param <T>   the type of the object to be constructed
  188.      * @param klass the class to be constructed.
  189.      * @param arg   the actual argument. May be null (this will result in calling the default constructor).
  190.      * @return new instance of {@code klazz}
  191.      * @throws NoSuchMethodException     If the constructor cannot be found
  192.      * @throws IllegalAccessException    If an error occurs accessing the constructor
  193.      * @throws InvocationTargetException If an error occurs invoking the constructor
  194.      * @throws InstantiationException    If an error occurs instantiating the class
  195.      * @see #invokeConstructor(Class, Object[], Class[])
  196.      */
  197.     public static <T> T invokeConstructor(final Class<T> klass, final Object arg)
  198.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  199.         final Object[] args = toArray(arg);
  200.         return invokeConstructor(klass, args);
  201.     }

  202.     /**
  203.      * <p>
  204.      * Returns new instance of {@code klazz</code> created using the actual arguments <code>args}. The formal parameter types are inferred from the actual
  205.      * values of {@code args}. See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.
  206.      * </p>
  207.      *
  208.      * <p>
  209.      * The signatures should be assignment compatible.
  210.      * </p>
  211.      *
  212.      * @param <T>   the type of the object to be constructed
  213.      * @param klass the class to be constructed.
  214.      * @param args  actual argument array. May be null (this will result in calling the default constructor).
  215.      * @return new instance of {@code klazz}
  216.      * @throws NoSuchMethodException     If the constructor cannot be found
  217.      * @throws IllegalAccessException    If an error occurs accessing the constructor
  218.      * @throws InvocationTargetException If an error occurs invoking the constructor
  219.      * @throws InstantiationException    If an error occurs instantiating the class
  220.      * @see #invokeConstructor(Class, Object[], Class[])
  221.      */
  222.     public static <T> T invokeConstructor(final Class<T> klass, Object[] args)
  223.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  224.         if (null == args) {
  225.             args = BeanUtils.EMPTY_OBJECT_ARRAY;
  226.         }
  227.         final int arguments = args.length;
  228.         final Class<?>[] parameterTypes = new Class<?>[arguments];
  229.         for (int i = 0; i < arguments; i++) {
  230.             parameterTypes[i] = args[i].getClass();
  231.         }
  232.         return invokeConstructor(klass, args, parameterTypes);
  233.     }

  234.     /**
  235.      * <p>
  236.      * Returns new instance of {@code klazz} created using constructor with signature {@code parameterTypes</code> and actual arguments <code>args}.
  237.      * </p>
  238.      *
  239.      * <p>
  240.      * The signatures should be assignment compatible.
  241.      * </p>
  242.      *
  243.      * @param <T>            the type of the object to be constructed
  244.      * @param klass          the class to be constructed.
  245.      * @param args           actual argument array. May be null (this will result in calling the default constructor).
  246.      * @param parameterTypes parameter types array
  247.      * @return new instance of {@code klazz}
  248.      * @throws NoSuchMethodException     if matching constructor cannot be found
  249.      * @throws IllegalAccessException    thrown on the constructor's invocation
  250.      * @throws InvocationTargetException thrown on the constructor's invocation
  251.      * @throws InstantiationException    thrown on the constructor's invocation
  252.      * @see Constructor#newInstance
  253.      */
  254.     public static <T> T invokeConstructor(final Class<T> klass, Object[] args, Class<?>[] parameterTypes)
  255.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  256.         if (parameterTypes == null) {
  257.             parameterTypes = BeanUtils.EMPTY_CLASS_ARRAY;
  258.         }
  259.         if (args == null) {
  260.             args = BeanUtils.EMPTY_OBJECT_ARRAY;
  261.         }

  262.         final Constructor<T> ctor = getMatchingAccessibleConstructor(klass, parameterTypes);
  263.         if (null == ctor) {
  264.             throw new NoSuchMethodException("No such accessible constructor on object: " + klass.getName());
  265.         }
  266.         return ctor.newInstance(args);
  267.     }

  268.     /**
  269.      * <p>
  270.      * Convenience method returning new instance of {@code klazz} using a single argument constructor. The formal parameter type is inferred from the actual
  271.      * values of {@code arg}. See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.
  272.      * </p>
  273.      *
  274.      * <p>
  275.      * The signatures should match exactly.
  276.      * </p>
  277.      *
  278.      * @param <T>   the type of the object to be constructed
  279.      * @param klass the class to be constructed.
  280.      * @param arg   the actual argument. May be null (this will result in calling the default constructor).
  281.      * @return new instance of {@code klazz}
  282.      * @throws NoSuchMethodException     If the constructor cannot be found
  283.      * @throws IllegalAccessException    If an error occurs accessing the constructor
  284.      * @throws InvocationTargetException If an error occurs invoking the constructor
  285.      * @throws InstantiationException    If an error occurs instantiating the class
  286.      * @see #invokeExactConstructor(Class, Object[], Class[])
  287.      */
  288.     public static <T> T invokeExactConstructor(final Class<T> klass, final Object arg)
  289.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  290.         final Object[] args = toArray(arg);
  291.         return invokeExactConstructor(klass, args);
  292.     }

  293.     /**
  294.      * <p>
  295.      * Returns new instance of {@code klazz</code> created using the actual arguments <code>args}. The formal parameter types are inferred from the actual
  296.      * values of {@code args}. See {@link #invokeExactConstructor(Class, Object[], Class[])} for more details.
  297.      * </p>
  298.      *
  299.      * <p>
  300.      * The signatures should match exactly.
  301.      * </p>
  302.      *
  303.      * @param <T>   the type of the object to be constructed
  304.      * @param klass the class to be constructed.
  305.      * @param args  actual argument array. May be null (this will result in calling the default constructor).
  306.      * @return new instance of {@code klazz}
  307.      * @throws NoSuchMethodException     If the constructor cannot be found
  308.      * @throws IllegalAccessException    If an error occurs accessing the constructor
  309.      * @throws InvocationTargetException If an error occurs invoking the constructor
  310.      * @throws InstantiationException    If an error occurs instantiating the class
  311.      * @see #invokeExactConstructor(Class, Object[], Class[])
  312.      */
  313.     public static <T> T invokeExactConstructor(final Class<T> klass, Object[] args)
  314.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  315.         if (null == args) {
  316.             args = BeanUtils.EMPTY_OBJECT_ARRAY;
  317.         }
  318.         final int arguments = args.length;
  319.         final Class<?>[] parameterTypes = new Class[arguments];
  320.         for (int i = 0; i < arguments; i++) {
  321.             parameterTypes[i] = args[i].getClass();
  322.         }
  323.         return invokeExactConstructor(klass, args, parameterTypes);
  324.     }

  325.     /**
  326.      * <p>
  327.      * Returns new instance of {@code klazz} created using constructor with signature {@code parameterTypes} and actual arguments {@code args}.
  328.      * </p>
  329.      *
  330.      * <p>
  331.      * The signatures should match exactly.
  332.      * </p>
  333.      *
  334.      * @param <T>            the type of the object to be constructed
  335.      * @param klass          the class to be constructed.
  336.      * @param args           actual argument array. May be null (this will result in calling the default constructor).
  337.      * @param parameterTypes parameter types array
  338.      * @return new instance of {@code klazz}
  339.      * @throws NoSuchMethodException     if matching constructor cannot be found
  340.      * @throws IllegalAccessException    thrown on the constructor's invocation
  341.      * @throws InvocationTargetException thrown on the constructor's invocation
  342.      * @throws InstantiationException    thrown on the constructor's invocation
  343.      * @see Constructor#newInstance
  344.      */
  345.     public static <T> T invokeExactConstructor(final Class<T> klass, Object[] args, Class<?>[] parameterTypes)
  346.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

  347.         if (args == null) {
  348.             args = BeanUtils.EMPTY_OBJECT_ARRAY;
  349.         }

  350.         if (parameterTypes == null) {
  351.             parameterTypes = BeanUtils.EMPTY_CLASS_ARRAY;
  352.         }

  353.         final Constructor<T> ctor = getAccessibleConstructor(klass, parameterTypes);
  354.         if (null == ctor) {
  355.             throw new NoSuchMethodException("No such accessible constructor on object: " + klass.getName());
  356.         }
  357.         return ctor.newInstance(args);
  358.     }

  359.     /**
  360.      * Delegates to {@link Array#newInstance(Class, int)}.
  361.      *
  362.      * @param <T>           Component type.
  363.      * @param componentType See {@link Array#newInstance(Class, int)}.
  364.      * @param length        See {@link Array#newInstance(Class, int)}.
  365.      * @return See {@link Array#newInstance(Class, int)}.
  366.      */
  367.     @SuppressWarnings("unchecked")
  368.     public static <T> T[] newArray(final Class<T> componentType, final int length) {
  369.         return (T[]) Array.newInstance(componentType, length);
  370.     }

  371.     private static Object[] toArray(final Object arg) {
  372.         Object[] args = null;
  373.         if (arg != null) {
  374.             args = new Object[] { arg };
  375.         }
  376.         return args;
  377.     }

  378.     private ConstructorUtils() {
  379.         // empty
  380.     }
  381. }