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 015package org.apache.tapestry5.ioc.internal.util; 016 017import org.apache.tapestry5.commons.ObjectCreator; 018import org.apache.tapestry5.commons.util.ExceptionUtils; 019import org.apache.tapestry5.ioc.Invokable; 020 021import java.lang.reflect.Constructor; 022import java.lang.reflect.InvocationTargetException; 023 024/** 025 * Wraps the invocation of a constructor (with exception reporting) as an {@link Invokable}. 026 * 027 * @since 5.3 028 */ 029public class ConstructorInvoker<T> implements Invokable<T> 030{ 031 private final Constructor<T> constructor; 032 033 private final ObjectCreator[] constructorParameters; 034 035 public ConstructorInvoker(Constructor constructor, ObjectCreator[] constructorParameters) 036 { 037 this.constructor = constructor; 038 this.constructorParameters = constructorParameters; 039 } 040 041 @Override 042 public T invoke() 043 { 044 Throwable fail; 045 046 Object[] realized = InternalUtils.realizeObjects(constructorParameters); 047 048 try 049 { 050 return constructor.newInstance(realized); 051 } catch (InvocationTargetException ex) 052 { 053 fail = ex.getTargetException(); 054 } catch (Exception ex) 055 { 056 fail = ex; 057 } 058 059 throw new RuntimeException(String.format("Error invoking constructor %s: %s", 060 constructor, ExceptionUtils.toMessage(fail)), fail); 061 } 062}