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.io.Serializable;
020import java.lang.reflect.Constructor;
021import java.lang.reflect.InvocationTargetException;
022
023import org.apache.commons.collections4.FunctorException;
024import org.apache.commons.collections4.Transformer;
025
026/**
027 * Transformer implementation that creates a new object instance by reflection.
028 *
029 * @since 3.0
030 * @version $Id: InstantiateTransformer.html 972421 2015-11-14 20:00:04Z tn $
031 */
032public class InstantiateTransformer<T> implements Transformer<Class<? extends T>, T>, Serializable {
033
034    /** The serial version */
035    private static final long serialVersionUID = 3786388740793356347L;
036
037    /** Singleton instance that uses the no arg constructor */
038    @SuppressWarnings("rawtypes")
039    private static final Transformer NO_ARG_INSTANCE = new InstantiateTransformer<Object>();
040
041    /** The constructor parameter types */
042    private final Class<?>[] iParamTypes;
043    /** The constructor arguments */
044    private final Object[] iArgs;
045
046    /**
047     * Get a typed no-arg instance.
048     *
049     * @param <T>  the type of the objects to be created
050     * @return Transformer<Class<? extends T>, T>
051     */
052    @SuppressWarnings("unchecked")
053    public static <T> Transformer<Class<? extends T>, T> instantiateTransformer() {
054        return (Transformer<Class<? extends T>, T>) NO_ARG_INSTANCE;
055    }
056
057    /**
058     * Transformer method that performs validation.
059     *
060     * @param <T>  the type of the objects to be created
061     * @param paramTypes  the constructor parameter types
062     * @param args  the constructor arguments
063     * @return an instantiate transformer
064     */
065    public static <T> Transformer<Class<? extends T>, T> instantiateTransformer(final Class<?>[] paramTypes,
066                                                                                final Object[] args) {
067        if (((paramTypes == null) && (args != null))
068            || ((paramTypes != null) && (args == null))
069            || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) {
070            throw new IllegalArgumentException("Parameter types must match the arguments");
071        }
072
073        if (paramTypes == null || paramTypes.length == 0) {
074            return new InstantiateTransformer<T>();
075        }
076        return new InstantiateTransformer<T>(paramTypes, args);
077    }
078
079    /**
080     * Constructor for no arg instance.
081     */
082    private InstantiateTransformer() {
083        super();
084        iParamTypes = null;
085        iArgs = null;
086    }
087
088    /**
089     * Constructor that performs no validation.
090     * Use <code>instantiateTransformer</code> 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        super();
099        iParamTypes = paramTypes != null ? paramTypes.clone() : null;
100        iArgs = args != null ? args.clone() : null;
101    }
102
103    /**
104     * Transforms the input Class object to a result by instantiation.
105     *
106     * @param input  the input object to transform
107     * @return the transformed result
108     */
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}