Search in sources :

Example 6 with AccessException

use of cn.taketoday.expression.AccessException in project today-framework by TAKETODAY.

the class ReflectiveConstructorResolver method resolve.

/**
 * Locate a constructor on the type. There are three kinds of match that might occur:
 * <ol>
 * <li>An exact match where the types of the arguments match the types of the constructor
 * <li>An in-exact match where the types we are looking for are subtypes of those defined on the constructor
 * <li>A match where we are able to convert the arguments into those expected by the constructor, according to the
 * registered type converter.
 * </ol>
 */
@Override
@Nullable
public ConstructorExecutor resolve(EvaluationContext context, String typeName, List<TypeDescriptor> argumentTypes) throws AccessException {
    try {
        TypeConverter typeConverter = context.getTypeConverter();
        Class<?> type = context.getTypeLocator().findType(typeName);
        Constructor<?>[] ctors = type.getConstructors();
        Arrays.sort(ctors, Comparator.comparingInt(Constructor::getParameterCount));
        Constructor<?> closeMatch = null;
        Constructor<?> matchRequiringConversion = null;
        for (Constructor<?> ctor : ctors) {
            int paramCount = ctor.getParameterCount();
            List<TypeDescriptor> paramDescriptors = new ArrayList<>(paramCount);
            for (int i = 0; i < paramCount; i++) {
                paramDescriptors.add(new TypeDescriptor(new MethodParameter(ctor, i)));
            }
            ReflectionHelper.ArgumentsMatchInfo matchInfo = null;
            if (ctor.isVarArgs() && argumentTypes.size() >= paramCount - 1) {
                // *sigh* complicated
                // Basically.. we have to have all parameters match up until the varargs one, then the rest of what is
                // being provided should be
                // the same type whilst the final argument to the method must be an array of that (oh, how easy...not) -
                // or the final parameter
                // we are supplied does match exactly (it is an array already).
                matchInfo = ReflectionHelper.compareArgumentsVarargs(paramDescriptors, argumentTypes, typeConverter);
            } else if (paramCount == argumentTypes.size()) {
                // worth a closer look
                matchInfo = ReflectionHelper.compareArguments(paramDescriptors, argumentTypes, typeConverter);
            }
            if (matchInfo != null) {
                if (matchInfo.isExactMatch()) {
                    return new ReflectiveConstructorExecutor(ctor);
                } else if (matchInfo.isCloseMatch()) {
                    closeMatch = ctor;
                } else if (matchInfo.isMatchRequiringConversion()) {
                    matchRequiringConversion = ctor;
                }
            }
        }
        if (closeMatch != null) {
            return new ReflectiveConstructorExecutor(closeMatch);
        } else if (matchRequiringConversion != null) {
            return new ReflectiveConstructorExecutor(matchRequiringConversion);
        } else {
            return null;
        }
    } catch (EvaluationException ex) {
        throw new AccessException("Failed to resolve constructor", ex);
    }
}
Also used : Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) EvaluationException(cn.taketoday.expression.EvaluationException) TypeConverter(cn.taketoday.expression.TypeConverter) AccessException(cn.taketoday.expression.AccessException) TypeDescriptor(cn.taketoday.core.TypeDescriptor) MethodParameter(cn.taketoday.core.MethodParameter) Nullable(cn.taketoday.lang.Nullable)

Example 7 with AccessException

use of cn.taketoday.expression.AccessException in project today-framework by TAKETODAY.

the class ReflectiveMethodExecutor method execute.

@Override
public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException {
    try {
        this.argumentConversionOccurred = ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.originalMethod, this.varargsPosition);
        if (this.originalMethod.isVarArgs()) {
            arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(this.originalMethod.getParameterTypes(), arguments);
        }
        ReflectionUtils.makeAccessible(this.methodToInvoke);
        Object value = this.methodToInvoke.invoke(target, arguments);
        return new TypedValue(value, new TypeDescriptor(new MethodParameter(this.originalMethod, -1)).narrow(value));
    } catch (Exception ex) {
        throw new AccessException("Problem invoking method: " + this.methodToInvoke, ex);
    }
}
Also used : AccessException(cn.taketoday.expression.AccessException) TypeDescriptor(cn.taketoday.core.TypeDescriptor) MethodParameter(cn.taketoday.core.MethodParameter) AccessException(cn.taketoday.expression.AccessException) TypedValue(cn.taketoday.expression.TypedValue)

Example 8 with AccessException

use of cn.taketoday.expression.AccessException in project today-framework by TAKETODAY.

the class ReflectiveMethodResolver method resolve.

/**
 * Locate a method on a type. There are three kinds of match that might occur:
 * <ol>
 * <li>an exact match where the types of the arguments match the types of the constructor
 * <li>an in-exact match where the types we are looking for are subtypes of those defined on the constructor
 * <li>a match where we are able to convert the arguments into those expected by the constructor,
 * according to the registered type converter
 * </ol>
 */
@Override
@Nullable
public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, List<TypeDescriptor> argumentTypes) throws AccessException {
    try {
        TypeConverter typeConverter = context.getTypeConverter();
        Class<?> type = (targetObject instanceof Class ? (Class<?>) targetObject : targetObject.getClass());
        ArrayList<Method> methods = new ArrayList<>(getMethods(type, targetObject));
        // If a filter is registered for this type, call it
        MethodFilter filter = (this.filters != null ? this.filters.get(type) : null);
        if (filter != null) {
            List<Method> filtered = filter.filter(methods);
            methods = (filtered instanceof ArrayList ? (ArrayList<Method>) filtered : new ArrayList<>(filtered));
        }
        // Sort methods into a sensible order
        if (methods.size() > 1) {
            methods.sort((m1, m2) -> {
                int m1pl = m1.getParameterCount();
                int m2pl = m2.getParameterCount();
                // vararg methods go last
                if (m1pl == m2pl) {
                    if (!m1.isVarArgs() && m2.isVarArgs()) {
                        return -1;
                    } else if (m1.isVarArgs() && !m2.isVarArgs()) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
                return Integer.compare(m1pl, m2pl);
            });
        }
        // Resolve any bridge methods
        for (int i = 0; i < methods.size(); i++) {
            methods.set(i, BridgeMethodResolver.findBridgedMethod(methods.get(i)));
        }
        // Remove duplicate methods (possible due to resolved bridge methods)
        Set<Method> methodsToIterate = new LinkedHashSet<>(methods);
        Method closeMatch = null;
        int closeMatchDistance = Integer.MAX_VALUE;
        Method matchRequiringConversion = null;
        boolean multipleOptions = false;
        for (Method method : methodsToIterate) {
            if (method.getName().equals(name)) {
                int paramCount = method.getParameterCount();
                List<TypeDescriptor> paramDescriptors = new ArrayList<>(paramCount);
                for (int i = 0; i < paramCount; i++) {
                    paramDescriptors.add(new TypeDescriptor(new MethodParameter(method, i)));
                }
                ReflectionHelper.ArgumentsMatchInfo matchInfo = null;
                if (method.isVarArgs() && argumentTypes.size() >= (paramCount - 1)) {
                    // *sigh* complicated
                    matchInfo = ReflectionHelper.compareArgumentsVarargs(paramDescriptors, argumentTypes, typeConverter);
                } else if (paramCount == argumentTypes.size()) {
                    // Name and parameter number match, check the arguments
                    matchInfo = ReflectionHelper.compareArguments(paramDescriptors, argumentTypes, typeConverter);
                }
                if (matchInfo != null) {
                    if (matchInfo.isExactMatch()) {
                        return new ReflectiveMethodExecutor(method, type);
                    } else if (matchInfo.isCloseMatch()) {
                        if (this.useDistance) {
                            int matchDistance = ReflectionHelper.getTypeDifferenceWeight(paramDescriptors, argumentTypes);
                            if (closeMatch == null || matchDistance < closeMatchDistance) {
                                // This is a better match...
                                closeMatch = method;
                                closeMatchDistance = matchDistance;
                            }
                        } else {
                            // Take this as a close match if there isn't one already
                            if (closeMatch == null) {
                                closeMatch = method;
                            }
                        }
                    } else if (matchInfo.isMatchRequiringConversion()) {
                        if (matchRequiringConversion != null) {
                            multipleOptions = true;
                        }
                        matchRequiringConversion = method;
                    }
                }
            }
        }
        if (closeMatch != null) {
            return new ReflectiveMethodExecutor(closeMatch, type);
        } else if (matchRequiringConversion != null) {
            if (multipleOptions) {
                throw new SpelEvaluationException(SpelMessage.MULTIPLE_POSSIBLE_METHODS, name);
            }
            return new ReflectiveMethodExecutor(matchRequiringConversion, type);
        } else {
            return null;
        }
    } catch (EvaluationException ex) {
        throw new AccessException("Failed to resolve method", ex);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SpelEvaluationException(cn.taketoday.expression.spel.SpelEvaluationException) MethodFilter(cn.taketoday.expression.MethodFilter) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) EvaluationException(cn.taketoday.expression.EvaluationException) SpelEvaluationException(cn.taketoday.expression.spel.SpelEvaluationException) TypeConverter(cn.taketoday.expression.TypeConverter) AccessException(cn.taketoday.expression.AccessException) TypeDescriptor(cn.taketoday.core.TypeDescriptor) MethodParameter(cn.taketoday.core.MethodParameter) Nullable(cn.taketoday.lang.Nullable)

Example 9 with AccessException

use of cn.taketoday.expression.AccessException in project today-framework by TAKETODAY.

the class SpelReproTests method SPR9495.

@Test
void SPR9495() {
    SpelParserConfiguration configuration = new SpelParserConfiguration(false, false);
    ExpressionParser parser = new SpelExpressionParser(configuration);
    StandardEvaluationContext context = new StandardEvaluationContext();
    Expression spel = parser.parseExpression("#enumType.values()");
    context.setVariable("enumType", ABC.class);
    Object result = spel.getValue(context);
    assertThat(result).isNotNull();
    assertThat(result.getClass().isArray()).isTrue();
    assertThat(Array.get(result, 0)).isEqualTo(ABC.A);
    assertThat(Array.get(result, 1)).isEqualTo(ABC.B);
    assertThat(Array.get(result, 2)).isEqualTo(ABC.C);
    context.addMethodResolver(new MethodResolver() {

        @Override
        public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, List<TypeDescriptor> argumentTypes) throws AccessException {
            return (context1, target, arguments) -> {
                try {
                    Method method = XYZ.class.getMethod("values");
                    Object value = method.invoke(target, arguments);
                    return new TypedValue(value, new TypeDescriptor(new MethodParameter(method, -1)).narrow(value));
                } catch (Exception ex) {
                    throw new AccessException(ex.getMessage(), ex);
                }
            };
        }
    });
    result = spel.getValue(context);
    assertThat(result).isNotNull();
    assertThat(result.getClass().isArray()).isTrue();
    assertThat(Array.get(result, 0)).isEqualTo(XYZ.X);
    assertThat(Array.get(result, 1)).isEqualTo(XYZ.Y);
    assertThat(Array.get(result, 2)).isEqualTo(XYZ.Z);
}
Also used : StandardEvaluationContext(cn.taketoday.expression.spel.support.StandardEvaluationContext) ReflectiveMethodResolver(cn.taketoday.expression.spel.support.ReflectiveMethodResolver) MethodResolver(cn.taketoday.expression.MethodResolver) Method(java.lang.reflect.Method) EvaluationException(cn.taketoday.expression.EvaluationException) ExpressionException(cn.taketoday.expression.ExpressionException) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) AccessException(cn.taketoday.expression.AccessException) SpelExpressionParser(cn.taketoday.expression.spel.standard.SpelExpressionParser) AccessException(cn.taketoday.expression.AccessException) TypeDescriptor(cn.taketoday.core.TypeDescriptor) Expression(cn.taketoday.expression.Expression) SpelExpression(cn.taketoday.expression.spel.standard.SpelExpression) MethodExecutor(cn.taketoday.expression.MethodExecutor) ExpressionParser(cn.taketoday.expression.ExpressionParser) SpelExpressionParser(cn.taketoday.expression.spel.standard.SpelExpressionParser) EvaluationContext(cn.taketoday.expression.EvaluationContext) StandardEvaluationContext(cn.taketoday.expression.spel.support.StandardEvaluationContext) MethodParameter(cn.taketoday.core.MethodParameter) TypedValue(cn.taketoday.expression.TypedValue) Test(org.junit.jupiter.api.Test)

Example 10 with AccessException

use of cn.taketoday.expression.AccessException in project today-infrastructure by TAKETODAY.

the class ReflectiveMethodExecutor method execute.

@Override
public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException {
    try {
        this.argumentConversionOccurred = ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.originalMethod, this.varargsPosition);
        if (this.originalMethod.isVarArgs()) {
            arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(this.originalMethod.getParameterTypes(), arguments);
        }
        ReflectionUtils.makeAccessible(this.methodToInvoke);
        Object value = this.methodToInvoke.invoke(target, arguments);
        return new TypedValue(value, new TypeDescriptor(new MethodParameter(this.originalMethod, -1)).narrow(value));
    } catch (Exception ex) {
        throw new AccessException("Problem invoking method: " + this.methodToInvoke, ex);
    }
}
Also used : AccessException(cn.taketoday.expression.AccessException) TypeDescriptor(cn.taketoday.core.TypeDescriptor) MethodParameter(cn.taketoday.core.MethodParameter) AccessException(cn.taketoday.expression.AccessException) TypedValue(cn.taketoday.expression.TypedValue)

Aggregations

AccessException (cn.taketoday.expression.AccessException)12 MethodParameter (cn.taketoday.core.MethodParameter)8 TypeDescriptor (cn.taketoday.core.TypeDescriptor)8 EvaluationException (cn.taketoday.expression.EvaluationException)6 TypedValue (cn.taketoday.expression.TypedValue)6 Expression (cn.taketoday.expression.Expression)4 TypeConverter (cn.taketoday.expression.TypeConverter)4 SpelExpression (cn.taketoday.expression.spel.standard.SpelExpression)4 SpelExpressionParser (cn.taketoday.expression.spel.standard.SpelExpressionParser)4 StandardEvaluationContext (cn.taketoday.expression.spel.support.StandardEvaluationContext)4 Nullable (cn.taketoday.lang.Nullable)4 Method (java.lang.reflect.Method)4 ArrayList (java.util.ArrayList)4 Test (org.junit.jupiter.api.Test)4 EvaluationContext (cn.taketoday.expression.EvaluationContext)2 ExpressionException (cn.taketoday.expression.ExpressionException)2 ExpressionParser (cn.taketoday.expression.ExpressionParser)2 MethodExecutor (cn.taketoday.expression.MethodExecutor)2 MethodFilter (cn.taketoday.expression.MethodFilter)2 MethodResolver (cn.taketoday.expression.MethodResolver)2