001    // Copyright 2011 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    // http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    
016    package org.apache.tapestry5.ioc.internal.util;
017    
018    import org.apache.tapestry5.ioc.Invokable;
019    import org.apache.tapestry5.ioc.ObjectCreator;
020    
021    import java.lang.reflect.InvocationTargetException;
022    import java.lang.reflect.Method;
023    
024    /**
025     * @since 5.3
026     */
027    public class MethodInvoker<T> implements Invokable<T>
028    {
029        private final Object instance;
030    
031        private final Method method;
032    
033        private final ObjectCreator[] methodParameters;
034    
035        public MethodInvoker(Object instance, Method method, ObjectCreator[] methodParameters)
036        {
037            this.instance = instance;
038            this.method = method;
039            this.methodParameters = methodParameters;
040        }
041    
042        public T invoke()
043        {
044            Throwable fail;
045    
046            Object[] realized = InternalUtils.realizeObjects(methodParameters);
047    
048            try
049            {
050                Object result = method.invoke(instance, realized);
051    
052                return (T) result;
053            } catch (InvocationTargetException ex)
054            {
055                fail = ex.getTargetException();
056            } catch (Exception ex)
057            {
058                fail = ex;
059            }
060    
061            throw new RuntimeException(String.format("Error invoking method %s: %s",
062                    method, InternalUtils.toMessage(fail)), fail);
063        }
064    }