Example usage for org.springframework.util ReflectionUtils invokeMethod

List of usage examples for org.springframework.util ReflectionUtils invokeMethod

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils invokeMethod.

Prototype

@Nullable
public static Object invokeMethod(Method method, @Nullable Object target, @Nullable Object... args) 

Source Link

Document

Invoke the specified Method against the supplied target object with the supplied arguments.

Usage

From source file:org.springframework.orm.hibernate5.HibernateTemplate.java

@Deprecated
@Override//from   w w w . j a  va  2 s.c  o m
@SuppressWarnings({ "rawtypes", "deprecation" })
public Iterator<?> iterate(final String queryString, @Nullable final Object... values)
        throws DataAccessException {
    return nonNull(executeWithNativeSession((HibernateCallback<Iterator<?>>) session -> {
        org.hibernate.Query queryObject = queryObject(
                ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
        prepareQuery(queryObject);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                queryObject.setParameter(i, values[i]);
            }
        }
        return queryObject.iterate();
    }));
}

From source file:org.springframework.orm.hibernate5.HibernateTemplate.java

@Deprecated
@Override//from   w w  w .  j  av a  2s  .c om
@SuppressWarnings({ "rawtypes", "deprecation" })
public int bulkUpdate(final String queryString, @Nullable final Object... values) throws DataAccessException {
    Integer result = executeWithNativeSession(session -> {
        org.hibernate.Query queryObject = queryObject(
                ReflectionUtils.invokeMethod(createQueryMethod, session, queryString));
        prepareQuery(queryObject);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                queryObject.setParameter(i, values[i]);
            }
        }
        return queryObject.executeUpdate();
    });
    Assert.state(result != null, "No update count");
    return result;
}

From source file:org.springframework.test.util.ReflectionTestUtils.java

/**
 * Invoke the setter method with the given {@code name} on the supplied
 * target object with the supplied {@code value}.
 * <p>This method traverses the class hierarchy in search of the desired
 * method. In addition, an attempt will be made to make non-{@code public}
 * methods <em>accessible</em>, thus allowing one to invoke {@code protected},
 * {@code private}, and <em>package-private</em> setter methods.
 * <p>In addition, this method supports JavaBean-style <em>property</em>
 * names. For example, if you wish to set the {@code name} property on the
 * target object, you may pass either &quot;name&quot; or
 * &quot;setName&quot; as the method name.
 * @param target the target object on which to invoke the specified setter
 * method//from w w  w  . j  a  v  a2 s .c o m
 * @param name the name of the setter method to invoke or the corresponding
 * property name
 * @param value the value to provide to the setter method
 * @param type the formal parameter type declared by the setter method
 * @see ReflectionUtils#findMethod(Class, String, Class[])
 * @see ReflectionUtils#makeAccessible(Method)
 * @see ReflectionUtils#invokeMethod(Method, Object, Object[])
 */
public static void invokeSetterMethod(Object target, String name, @Nullable Object value,
        @Nullable Class<?> type) {
    Assert.notNull(target, "Target object must not be null");
    Assert.hasText(name, "Method name must not be empty");
    Class<?>[] paramTypes = (type != null ? new Class<?>[] { type } : null);

    String setterMethodName = name;
    if (!name.startsWith(SETTER_PREFIX)) {
        setterMethodName = SETTER_PREFIX + StringUtils.capitalize(name);
    }

    Method method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
    if (method == null && !setterMethodName.equals(name)) {
        setterMethodName = name;
        method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
    }
    if (method == null) {
        throw new IllegalArgumentException(
                String.format("Could not find setter method '%s' on %s with parameter type [%s]",
                        setterMethodName, safeToString(target), type));
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Invoking setter method '%s' on %s with value [%s]", setterMethodName,
                safeToString(target), value));
    }

    ReflectionUtils.makeAccessible(method);
    ReflectionUtils.invokeMethod(method, target, value);
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeValidateMethodForCurrentState(Object model) {
    String methodName = "validate" + StringUtils.capitalize(requestContext.getCurrentState().getId());
    // preferred/*from   w  w  w  . j  a  v  a  2  s  .c  om*/
    Method validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName,
            new Class[] { ValidationContext.class });
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Invoking current state model validation method '" + methodName + "(ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // web flow 2.0.3 or < compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName,
            new Class[] { MessageContext.class });
    if (validateMethod != null) {
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { requestContext.getMessageContext() });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName, new Class[] { Errors.class });
    if (validateMethod != null) {
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking current state model validation method '" + methodName + "(Errors)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { errors });
        return true;
    }
    return false;
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeDefaultValidateMethod(Object model) {
    // preferred/*from  w  ww .  ja v a2s .  c  o m*/
    Method validateMethod = ReflectionUtils.findMethod(model.getClass(), "validate",
            new Class[] { ValidationContext.class });
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking default model validation method 'validate(ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), "validate", new Class[] { Errors.class });
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking default model validation method 'validate(Errors)'");
        }
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { errors });
        return true;
    }
    return false;
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeValidatorValidateMethodForCurrentState(Object model, Object validator) {
    String methodName = "validate" + StringUtils.capitalize(requestContext.getCurrentState().getId());
    // preferred/* w  w  w . j a va  2 s .c  o  m*/
    Method validateMethod = findValidationMethod(model, validator, methodName, ValidationContext.class);
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking current state validator method '"
                    + ClassUtils.getShortName(validator.getClass()) + "." + methodName + "("
                    + ClassUtils.getShortName(model.getClass()) + ", ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, validator,
                new Object[] { model, new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = findValidationMethod(model, validator, methodName, Errors.class);
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking current state validator method '"
                    + ClassUtils.getShortName(validator.getClass()) + "." + methodName + "("
                    + ClassUtils.getShortName(model.getClass()) + ", Errors)'");
        }
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        ReflectionUtils.invokeMethod(validateMethod, validator, new Object[] { model, errors });
        return true;
    }
    // web flow 2.0.0 to 2.0.3 compatibility only [to remove in web flow 3]
    validateMethod = findValidationMethod(model, validator, methodName, MessageContext.class);
    if (validateMethod != null) {
        ReflectionUtils.invokeMethod(validateMethod, validator,
                new Object[] { model, requestContext.getMessageContext() });
        return true;
    }
    return false;
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeValidatorDefaultValidateMethod(Object model, Object validator) {
    if (validator instanceof Validator) {
        // Spring Framework Validator type
        Validator springValidator = (Validator) validator;
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking Spring Validator '" + ClassUtils.getShortName(validator.getClass()) + "'");
        }/*from   ww  w .  j  a  va 2s .  c  o m*/
        if (springValidator.supports(model.getClass())) {
            MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(),
                    modelName, model, expressionParser, messageCodesResolver, mappingResults);
            springValidator.validate(model, errors);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Spring Validator '" + ClassUtils.getShortName(validator.getClass())
                        + "' doesn't support model class " + model.getClass());
            }
        }
        return true;
    }
    // preferred
    Method validateMethod = findValidationMethod(model, validator, "validate", ValidationContext.class);
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking default validator method '" + ClassUtils.getShortName(validator.getClass())
                    + ".validate(" + ClassUtils.getShortName(model.getClass()) + ", ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, validator,
                new Object[] { model, new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = findValidationMethod(model, validator, "validate", Errors.class);
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking default validator method '" + ClassUtils.getShortName(validator.getClass())
                    + ".validate(" + ClassUtils.getShortName(model.getClass()) + ", Errors)'");
        }
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        ReflectionUtils.invokeMethod(validateMethod, validator, new Object[] { model, errors });
        return true;
    }
    return false;
}

From source file:org.springframework.yarn.support.compat.NMTokenCacheCompat.java

public static boolean containsToken(NMTokenCache nmTokenCache, String nodeId) {
    if (nmTokenCache != null) {
        Method method = ReflectionUtils.findMethod(NMTokenCache.class, "containsNMToken", String.class);
        if (method == null) {
            method = ReflectionUtils.findMethod(NMTokenCache.class, "containsToken", String.class);
        }/*from w w w .j av a2 s. co  m*/
        if (method != null) {
            boolean results = (Boolean) ReflectionUtils.invokeMethod(method, nmTokenCache, nodeId);
            log.debug("NMTokenCache method " + method.getName() + " returned " + results);
            return results;
        } else {
            log.debug("Unable to determine the name for 'containsToken' method on NMTokenCache class");
        }
    }
    return false;
}

From source file:org.springframework.yarn.support.compat.ResourceCompat.java

/**
 * Invokes {@link Resource#setVirtualCores(int)}.
 *
 * @param resource the target object//from   ww  w. j a  v a 2  s . com
 * @param vCores the vCores
 */
public static void setVirtualCores(Resource resource, int vCores) {
    if (setVirtualCores == null) {
        setVirtualCores = ReflectionUtils.findMethod(Resource.class, "setVirtualCores", int.class);
    }
    if (setVirtualCores != null) {
        ReflectionUtils.invokeMethod(setVirtualCores, resource, vCores);
    } else {
        log.warn("Method setVirtualCores(int) is not implemented");
    }
}

From source file:org.squashtest.tm.service.internal.batchimport.excel.ReflectionMutatorSetter.java

/**
 * @see org.squashtest.tm.service.internal.batchimport.excel.PropertySetter#set(java.lang.Object, java.lang.Object)
 *//*from  w  w w .  j  a va  2s.  com*/
@Override
public void set(VAL value, TARGET target) {
    if (optionalValue && value == null) {
        return;
    }
    if (!optionalValue && value == null) {
        throw new NullMandatoryValueException(mutatorName);
    }

    if (mutator == null) {
        mutator = ReflectionUtils.findMethod(target.getClass(), mutatorName, paramType(value));

        if (mutator == null) {
            throw new IllegalStateException("Could not find method named '" + mutatorName + "("
                    + paramType(value) + ")' in object of type '" + target.getClass()
                    + "'. Maybe you mistyped field name.");
        }

        mutator.setAccessible(true);
    }

    ReflectionUtils.invokeMethod(mutator, target, value);
}