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.InvocationTargetException;
021import java.lang.reflect.Method;
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: InvokerTransformer.html 972421 2015-11-14 20:00:04Z tn $
031 */
032public class InvokerTransformer<I, O> implements Transformer<I, O>, Serializable {
033
034    /** The serial version */
035    private static final long serialVersionUID = -8653385846894047688L;
036
037    /** The method name to call */
038    private final String iMethodName;
039    /** The array of reflection parameter types */
040    private final Class<?>[] iParamTypes;
041    /** The array of reflection arguments */
042    private final Object[] iArgs;
043
044    /**
045     * Gets an instance of this transformer calling a specific method with no arguments.
046     *
047     * @param <I>  the input type
048     * @param <O>  the output type
049     * @param methodName  the method name to call
050     * @return an invoker transformer
051     * @since 3.1
052     */
053    public static <I, O> Transformer<I, O> invokerTransformer(final String methodName) {
054        if (methodName == null) {
055            throw new IllegalArgumentException("The method to invoke must not be null");
056        }
057        return new InvokerTransformer<I, O>(methodName);
058    }
059
060    /**
061     * Gets an instance of this transformer calling a specific method with specific values.
062     *
063     * @param <I>  the input type
064     * @param <O>  the output type
065     * @param methodName  the method name to call
066     * @param paramTypes  the parameter types of the method
067     * @param args  the arguments to pass to the method
068     * @return an invoker transformer
069     */
070    public static <I, O> Transformer<I, O> invokerTransformer(final String methodName, final Class<?>[] paramTypes,
071                                                              final Object[] args) {
072        if (methodName == null) {
073            throw new IllegalArgumentException("The method to invoke must not be null");
074        }
075        if (((paramTypes == null) && (args != null))
076            || ((paramTypes != null) && (args == null))
077            || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) {
078            throw new IllegalArgumentException("The parameter types must match the arguments");
079        }
080        if (paramTypes == null || paramTypes.length == 0) {
081            return new InvokerTransformer<I, O>(methodName);
082        }
083        return new InvokerTransformer<I, O>(methodName, paramTypes, args);
084    }
085
086    /**
087     * Constructor for no arg instance.
088     *
089     * @param methodName  the method to call
090     */
091    private InvokerTransformer(final String methodName) {
092        super();
093        iMethodName = methodName;
094        iParamTypes = null;
095        iArgs = null;
096    }
097
098    /**
099     * Constructor that performs no validation.
100     * Use <code>invokerTransformer</code> if you want that.
101     * <p>
102     * Note: from 4.0, the input parameters will be cloned
103     *
104     * @param methodName  the method to call
105     * @param paramTypes  the constructor parameter types
106     * @param args  the constructor arguments
107     */
108    public InvokerTransformer(final String methodName, final Class<?>[] paramTypes, final Object[] args) {
109        super();
110        iMethodName = methodName;
111        iParamTypes = paramTypes != null ? paramTypes.clone() : null;
112        iArgs = args != null ? args.clone() : null;
113    }
114
115    /**
116     * Transforms the input to result by invoking a method on the input.
117     *
118     * @param input  the input object to transform
119     * @return the transformed result, null if null input
120     */
121    @SuppressWarnings("unchecked")
122    public O transform(final Object input) {
123        if (input == null) {
124            return null;
125        }
126        try {
127            final Class<?> cls = input.getClass();
128            final Method method = cls.getMethod(iMethodName, iParamTypes);
129            return (O) method.invoke(input, iArgs);
130        } catch (final NoSuchMethodException ex) {
131            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
132                                       input.getClass() + "' does not exist");
133        } catch (final IllegalAccessException ex) {
134            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
135                                       input.getClass() + "' cannot be accessed");
136        } catch (final InvocationTargetException ex) {
137            throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" +
138                                       input.getClass() + "' threw an exception", ex);
139        }
140    }
141
142}