Search in sources :

Example 6 with TypeConverter

use of cn.taketoday.expression.TypeConverter 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 7 with TypeConverter

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

the class FunctionReference method executeFunctionJLRMethod.

/**
 * Execute a function represented as a {@code java.lang.reflect.Method}.
 *
 * @param state the expression evaluation state
 * @param method the method to invoke
 * @return the return value of the invoked Java method
 * @throws EvaluationException if there is any problem invoking the method
 */
private TypedValue executeFunctionJLRMethod(ExpressionState state, Method method) throws EvaluationException {
    Object[] functionArgs = getArguments(state);
    if (!method.isVarArgs()) {
        int declaredParamCount = method.getParameterCount();
        if (declaredParamCount != functionArgs.length) {
            throw new SpelEvaluationException(SpelMessage.INCORRECT_NUMBER_OF_ARGUMENTS_TO_FUNCTION, functionArgs.length, declaredParamCount);
        }
    }
    if (!Modifier.isStatic(method.getModifiers())) {
        throw new SpelEvaluationException(getStartPosition(), SpelMessage.FUNCTION_MUST_BE_STATIC, ClassUtils.getQualifiedMethodName(method), this.name);
    }
    // Convert arguments if necessary and remap them for varargs if required
    TypeConverter converter = state.getEvaluationContext().getTypeConverter();
    boolean argumentConversionOccurred = ReflectionHelper.convertAllArguments(converter, functionArgs, method);
    if (method.isVarArgs()) {
        functionArgs = ReflectionHelper.setupArgumentsForVarargsInvocation(method.getParameterTypes(), functionArgs);
    }
    boolean compilable = false;
    try {
        ReflectionUtils.makeAccessible(method);
        Object result = method.invoke(method.getClass(), functionArgs);
        compilable = !argumentConversionOccurred;
        return new TypedValue(result, new TypeDescriptor(new MethodParameter(method, -1)).narrow(result));
    } catch (Exception ex) {
        throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_FUNCTION_CALL, this.name, ex.getMessage());
    } finally {
        if (compilable) {
            this.exitTypeDescriptor = CodeFlow.toDescriptor(method.getReturnType());
            this.method = method;
        } else {
            this.exitTypeDescriptor = null;
            this.method = null;
        }
    }
}
Also used : TypeConverter(cn.taketoday.expression.TypeConverter) SpelEvaluationException(cn.taketoday.expression.spel.SpelEvaluationException) TypeDescriptor(cn.taketoday.core.TypeDescriptor) MethodParameter(cn.taketoday.core.MethodParameter) EvaluationException(cn.taketoday.expression.EvaluationException) SpelEvaluationException(cn.taketoday.expression.spel.SpelEvaluationException) TypedValue(cn.taketoday.expression.TypedValue)

Example 8 with TypeConverter

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

the class FunctionReference method executeFunctionJLRMethod.

/**
 * Execute a function represented as a {@code java.lang.reflect.Method}.
 *
 * @param state the expression evaluation state
 * @param method the method to invoke
 * @return the return value of the invoked Java method
 * @throws EvaluationException if there is any problem invoking the method
 */
private TypedValue executeFunctionJLRMethod(ExpressionState state, Method method) throws EvaluationException {
    Object[] functionArgs = getArguments(state);
    if (!method.isVarArgs()) {
        int declaredParamCount = method.getParameterCount();
        if (declaredParamCount != functionArgs.length) {
            throw new SpelEvaluationException(SpelMessage.INCORRECT_NUMBER_OF_ARGUMENTS_TO_FUNCTION, functionArgs.length, declaredParamCount);
        }
    }
    if (!Modifier.isStatic(method.getModifiers())) {
        throw new SpelEvaluationException(getStartPosition(), SpelMessage.FUNCTION_MUST_BE_STATIC, ClassUtils.getQualifiedMethodName(method), this.name);
    }
    // Convert arguments if necessary and remap them for varargs if required
    TypeConverter converter = state.getEvaluationContext().getTypeConverter();
    boolean argumentConversionOccurred = ReflectionHelper.convertAllArguments(converter, functionArgs, method);
    if (method.isVarArgs()) {
        functionArgs = ReflectionHelper.setupArgumentsForVarargsInvocation(method.getParameterTypes(), functionArgs);
    }
    boolean compilable = false;
    try {
        ReflectionUtils.makeAccessible(method);
        Object result = method.invoke(method.getClass(), functionArgs);
        compilable = !argumentConversionOccurred;
        return new TypedValue(result, new TypeDescriptor(new MethodParameter(method, -1)).narrow(result));
    } catch (Exception ex) {
        throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.EXCEPTION_DURING_FUNCTION_CALL, this.name, ex.getMessage());
    } finally {
        if (compilable) {
            this.exitTypeDescriptor = CodeFlow.toDescriptor(method.getReturnType());
            this.method = method;
        } else {
            this.exitTypeDescriptor = null;
            this.method = null;
        }
    }
}
Also used : TypeConverter(cn.taketoday.expression.TypeConverter) SpelEvaluationException(cn.taketoday.expression.spel.SpelEvaluationException) TypeDescriptor(cn.taketoday.core.TypeDescriptor) MethodParameter(cn.taketoday.core.MethodParameter) EvaluationException(cn.taketoday.expression.EvaluationException) SpelEvaluationException(cn.taketoday.expression.spel.SpelEvaluationException) TypedValue(cn.taketoday.expression.TypedValue)

Example 9 with TypeConverter

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

the class ConvertTest method testCustom.

@Test
public void testCustom() {
    elp.getManager().addResolver(new TypeConverter() {

        @Override
        public Object convertToType(ExpressionContext context, Object obj, Class<?> type) {
            if (obj instanceof String && type == MyBean.class) {
                context.setPropertyResolved(true);
                return new MyBean((String) obj);
            }
            return null;
        }
    });
    Object val = elp.getValue("'John Doe'", MyBean.class);
    assertTrue(val instanceof MyBean);
    assertEquals(((MyBean) val).getName(), "John Doe");
}
Also used : TypeConverter(cn.taketoday.expression.TypeConverter) ExpressionContext(cn.taketoday.expression.ExpressionContext) Test(org.junit.jupiter.api.Test)

Aggregations

TypeConverter (cn.taketoday.expression.TypeConverter)9 MethodParameter (cn.taketoday.core.MethodParameter)6 TypeDescriptor (cn.taketoday.core.TypeDescriptor)6 EvaluationException (cn.taketoday.expression.EvaluationException)6 AccessException (cn.taketoday.expression.AccessException)4 SpelEvaluationException (cn.taketoday.expression.spel.SpelEvaluationException)4 Nullable (cn.taketoday.lang.Nullable)4 ArrayList (java.util.ArrayList)4 Test (org.junit.jupiter.api.Test)3 MethodFilter (cn.taketoday.expression.MethodFilter)2 TypedValue (cn.taketoday.expression.TypedValue)2 Constructor (java.lang.reflect.Constructor)2 Method (java.lang.reflect.Method)2 LinkedHashSet (java.util.LinkedHashSet)2 ExpressionContext (cn.taketoday.expression.ExpressionContext)1