001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.expression.spel.support;
018
019import java.lang.reflect.Constructor;
020
021import org.springframework.expression.AccessException;
022import org.springframework.expression.ConstructorExecutor;
023import org.springframework.expression.EvaluationContext;
024import org.springframework.expression.TypedValue;
025import org.springframework.lang.Nullable;
026import org.springframework.util.ReflectionUtils;
027
028/**
029 * A simple ConstructorExecutor implementation that runs a constructor using reflective
030 * invocation.
031 *
032 * @author Andy Clement
033 * @author Juergen Hoeller
034 * @since 3.0
035 */
036public class ReflectiveConstructorExecutor implements ConstructorExecutor {
037
038        private final Constructor<?> ctor;
039
040        @Nullable
041        private final Integer varargsPosition;
042
043
044        public ReflectiveConstructorExecutor(Constructor<?> ctor) {
045                this.ctor = ctor;
046                if (ctor.isVarArgs()) {
047                        this.varargsPosition = ctor.getParameterCount() - 1;
048                }
049                else {
050                        this.varargsPosition = null;
051                }
052        }
053
054        @Override
055        public TypedValue execute(EvaluationContext context, Object... arguments) throws AccessException {
056                try {
057                        ReflectionHelper.convertArguments(
058                                        context.getTypeConverter(), arguments, this.ctor, this.varargsPosition);
059                        if (this.ctor.isVarArgs()) {
060                                arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(
061                                                this.ctor.getParameterTypes(), arguments);
062                        }
063                        ReflectionUtils.makeAccessible(this.ctor);
064                        return new TypedValue(this.ctor.newInstance(arguments));
065                }
066                catch (Exception ex) {
067                        throw new AccessException("Problem invoking constructor: " + this.ctor, ex);
068                }
069        }
070
071        public Constructor<?> getConstructor() {
072                return this.ctor;
073        }
074
075}