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.ioc.Invokable; 018import org.apache.tapestry5.ioc.ObjectCreator; 019import org.apache.tapestry5.ioc.util.ExceptionUtils; 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 public T invoke() 042 { 043 Throwable fail; 044 045 Object[] realized = InternalUtils.realizeObjects(constructorParameters); 046 047 try 048 { 049 return constructor.newInstance(realized); 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 constructor %s: %s", 059 constructor, ExceptionUtils.toMessage(fail)), fail); 060 } 061}