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    @Override
044    public T invoke()
045    {
046        Throwable fail;
047
048        Object[] realized = InternalUtils.realizeObjects(methodParameters);
049
050        try
051        {
052            Object result = method.invoke(instance, realized);
053
054            return (T) result;
055        } catch (InvocationTargetException ex)
056        {
057            fail = ex.getTargetException();
058        } catch (Exception ex)
059        {
060            fail = ex;
061        }
062
063        throw new RuntimeException(String.format("Error invoking method %s: %s",
064                method, ExceptionUtils.toMessage(fail)), fail);
065    }
066}