001// Copyright 2011-2013 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
016package org.apache.tapestry5.ioc.internal.util;
017
018import org.apache.tapestry5.ioc.Invokable;
019import org.apache.tapestry5.ioc.ObjectCreator;
020import org.apache.tapestry5.ioc.util.ExceptionUtils;
021
022import java.lang.reflect.InvocationTargetException;
023import java.lang.reflect.Method;
024
025/**
026 * @since 5.3
027 */
028public class MethodInvoker<T> implements Invokable<T>
029{
030    private final Object instance;
031
032    private final Method method;
033
034    private final ObjectCreator[] methodParameters;
035
036    public MethodInvoker(Object instance, Method method, ObjectCreator[] methodParameters)
037    {
038        this.instance = instance;
039        this.method = method;
040        this.methodParameters = methodParameters;
041    }
042
043    public T invoke()
044    {
045        Throwable fail;
046
047        Object[] realized = InternalUtils.realizeObjects(methodParameters);
048
049        try
050        {
051            Object result = method.invoke(instance, realized);
052
053            return (T) result;
054        } catch (InvocationTargetException ex)
055        {
056            fail = ex.getTargetException();
057        } catch (Exception ex)
058        {
059            fail = ex;
060        }
061
062        throw new RuntimeException(String.format("Error invoking method %s: %s",
063                method, ExceptionUtils.toMessage(fail)), fail);
064    }
065}