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