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