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.collections4.functors;
018
019import java.lang.reflect.Constructor;
020import java.lang.reflect.InvocationTargetException;
021
022import org.apache.commons.collections4.FunctorException;
023import org.apache.commons.collections4.Transformer;
024
025/**
026 * Transformer implementation that creates a new object instance by reflection.
027 * <p>
028 * <b>WARNING:</b> from v4.1 onwards this class will <b>not</b> be serializable anymore
029 * in order to prevent potential remote code execution exploits. Please refer to
030 * <a href="https://issues.apache.org/jira/browse/COLLECTIONS-580">COLLECTIONS-580</a>
031 * for more details.
032 * </p>
033 *
034 * @since 3.0
035 */
036public class InstantiateTransformer<T> implements Transformer<Class<? extends T>, T> {
037
038    /** Singleton instance that uses the no arg constructor */
039    @SuppressWarnings("rawtypes")
040    private static final Transformer NO_ARG_INSTANCE = new InstantiateTransformer<>();
041
042    /**
043     * Gets a typed no-arg instance.
044     *
045     * @param <T>  the type of the objects to be created
046     * @return Transformer&lt;Class&lt;? extends T&gt;, T&gt;
047     */
048    public static <T> Transformer<Class<? extends T>, T> instantiateTransformer() {
049        return NO_ARG_INSTANCE;
050    }
051    /**
052     * Transformer method that performs validation.
053     *
054     * @param <T>  the type of the objects to be created
055     * @param paramTypes  the constructor parameter types
056     * @param args  the constructor arguments
057     * @return an instantiate transformer
058     * @throws IllegalArgumentException if paramTypes does not match args
059     */
060    public static <T> Transformer<Class<? extends T>, T> instantiateTransformer(final Class<?>[] paramTypes,
061                                                                                final Object[] args) {
062        if (paramTypes == null && args != null
063            || paramTypes != null && args == null
064            || paramTypes != null && args != null && paramTypes.length != args.length) {
065            throw new IllegalArgumentException("Parameter types must match the arguments");
066        }
067
068        if (paramTypes == null || paramTypes.length == 0) {
069            return new InstantiateTransformer<>();
070        }
071        return new InstantiateTransformer<>(paramTypes, args);
072    }
073
074    /** The constructor parameter types */
075    private final Class<?>[] iParamTypes;
076
077    /** The constructor arguments */
078    private final Object[] iArgs;
079
080    /**
081     * Constructor for no arg instance.
082     */
083    private InstantiateTransformer() {
084        iParamTypes = null;
085        iArgs = null;
086    }
087
088    /**
089     * Constructor that performs no validation.
090     * Use {@code instantiateTransformer} if you want that.
091     * <p>
092     * Note: from 4.0, the input parameters will be cloned
093     *
094     * @param paramTypes  the constructor parameter types
095     * @param args  the constructor arguments
096     */
097    public InstantiateTransformer(final Class<?>[] paramTypes, final Object[] args) {
098        iParamTypes = paramTypes != null ? paramTypes.clone() : null;
099        iArgs = args != null ? args.clone() : null;
100    }
101
102    /**
103     * Transforms the input Class object to a result by instantiation.
104     *
105     * @param input  the input object to transform
106     * @return the transformed result
107     */
108    @Override
109    public T transform(final Class<? extends T> input) {
110        try {
111            if (input == null) {
112                throw new FunctorException(
113                    "InstantiateTransformer: Input object was not an instanceof Class, it was a null object");
114            }
115            final Constructor<? extends T> con = input.getConstructor(iParamTypes);
116            return con.newInstance(iArgs);
117        } catch (final NoSuchMethodException ex) {
118            throw new FunctorException("InstantiateTransformer: The constructor must exist and be public ");
119        } catch (final InstantiationException ex) {
120            throw new FunctorException("InstantiateTransformer: InstantiationException", ex);
121        } catch (final IllegalAccessException ex) {
122            throw new FunctorException("InstantiateTransformer: Constructor must be public", ex);
123        } catch (final InvocationTargetException ex) {
124            throw new FunctorException("InstantiateTransformer: Constructor threw an exception", ex);
125        }
126    }
127
128}