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