Example usage for org.springframework.util ReflectionUtils findMethod

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

Introduction

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

Prototype

@Nullable
public static Method findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes) 

Source Link

Document

Attempt to find a Method on the supplied class with the supplied name and parameter types.

Usage

From source file:org.pentaho.proxy.creators.userdetailsservice.ProxyUserDetailsService.java

public ProxyUserDetailsService(Object sourceObject) {
    this.sourceObject = sourceObject;
    Class<? extends Object> clazz = sourceObject.getClass();
    loadUserByNameMethod = ReflectionUtils.findMethod(clazz, "loadUserByUsername",
            new Class[] { String.class });
    loadUserByNameReturnType = loadUserByNameMethod.getReturnType();
}

From source file:io.pivotal.spring.xd.jdbcgpfdist.TestUtils.java

@SuppressWarnings("unchecked")
public static <T> T callMethod(String name, Object target, Object[] args, Class<?>[] argsTypes)
        throws Exception {
    Class<?> clazz = target.getClass();
    Method method = ReflectionUtils.findMethod(clazz, name, argsTypes);

    if (method == null)
        throw new IllegalArgumentException(
                "Cannot find method '" + method + "' in the class hierarchy of " + target.getClass());
    method.setAccessible(true);//from   w  w  w.j  a v a  2  s  .  c o  m
    return (T) ReflectionUtils.invokeMethod(method, target, args);
}

From source file:fi.helsinki.opintoni.web.arguments.StudentNumberArgumentResolverTest.java

private static MethodParameter getMethodParam(String methodName, Class<?> argType) {
    return new MethodParameter(ReflectionUtils.findMethod(MyController.class, methodName, argType), 0);
}

From source file:org.springmodules.cache.util.Reflections.java

/**
 * <p>// w  w w .  j  av a2 s .c  o m
 * This method uses reflection to build a valid hash code.
 * </p>
 *
 * <p>
 * It uses <code>AccessibleObject.setAccessible</code> to gain access to
 * private fields. This means that it will throw a security exception if run
 * under a security manager, if the permissions are not set up correctly. It
 * is also not as efficient as testing explicitly.
 * </p>
 *
 * <p>
 * Transient members will not be used, as they are likely derived fields,
 * and not part of the value of the <code>Object</code>.
 * </p>
 *
 * <p>
 * Static fields will not be tested. Superclass fields will be included.
 * </p>
 *
 * @param obj
 *          the object to create a <code>hashCode</code> for
 * @return the generated hash code, or zero if the given object is
 *         <code>null</code>
 */
public static int reflectionHashCode(Object obj) {
    if (obj == null)
        return 0;

    Class targetClass = obj.getClass();
    if (Objects.isArrayOfPrimitives(obj) || Objects.isPrimitiveOrWrapper(targetClass)) {
        return Objects.nullSafeHashCode(obj);
    }

    if (targetClass.isArray()) {
        return reflectionHashCode((Object[]) obj);
    }

    if (obj instanceof Collection) {
        return reflectionHashCode((Collection) obj);
    }

    if (obj instanceof Map) {
        return reflectionHashCode((Map) obj);
    }

    // determine whether the object's class declares hashCode() or has a
    // superClass other than java.lang.Object that declares hashCode()
    Class clazz = (obj instanceof Class) ? (Class) obj : obj.getClass();
    Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]);

    if (hashCodeMethod != null) {
        return obj.hashCode();
    }

    // could not find a hashCode other than the one declared by java.lang.Object
    int hash = INITIAL_HASH;

    try {
        while (targetClass != null) {
            Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                int modifiers = field.getModifiers();

                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj));
                }
            }
            targetClass = targetClass.getSuperclass();
        }
    } catch (IllegalAccessException exception) {
        // ///CLOVER:OFF
        ReflectionUtils.handleReflectionException(exception);
        // ///CLOVER:ON
    }

    return hash;
}

From source file:com.alibaba.otter.shared.communication.core.impl.AbstractCommunicationEndpoint.java

/**
 * ?/* ww w  .  ja  v a 2s  .com*/
 */
public Object acceptEvent(Event event) {
    if (event instanceof HeartEvent) {
        return event; // ??
    }

    try {
        Object action = CommunicationRegistry.getAction(event.getType());
        if (action != null) {

            // ???
            String methodName = "on" + StringUtils.capitalize(event.getType().toString());
            Method method = ReflectionUtils.findMethod(action.getClass(), methodName,
                    new Class[] { event.getClass() });
            if (method == null) {
                methodName = DEFAULT_METHOD; // ?
                method = ReflectionUtils.findMethod(action.getClass(), methodName,
                        new Class[] { event.getClass() });

                if (method == null) { // ??Event?
                    method = ReflectionUtils.findMethod(action.getClass(), methodName,
                            new Class[] { Event.class });
                }
            }
            // ?,????
            if (method != null) {
                try {
                    ReflectionUtils.makeAccessible(method);
                    return method.invoke(action, new Object[] { event });
                } catch (Throwable e) {
                    throw new CommunicationException("method_invoke_error:" + methodName, e);
                }
            } else {
                throw new CommunicationException(
                        "no_method_error for[" + StringUtils.capitalize(event.getType().toString())
                                + "] in Class[" + action.getClass().getName() + "]");
            }

        }

        throw new CommunicationException("eventType_no_action", event.getType().name());
    } catch (RuntimeException e) {
        logger.error("endpoint_error", e);
        throw e;
    } catch (Exception e) {
        logger.error("endpoint_error", e);
        throw new CommunicationException(e);
    }
}

From source file:org.jboss.instrument.classloading.JBossModulesLoadTimeWeaver.java

public void addTransformer(ClassFileTransformer transformer) {
    try {//from w w w  .java 2s .com
        Field transformers = ReflectionUtils.findField(classLoader.getClass(), "transformer");
        transformers.setAccessible(true);
        Object delegatingTransformer = transformers.get(classLoader);
        Method ADD_TRANSFORMER = ReflectionUtils.findMethod(delegatingTransformer.getClass(), "addTransformer",
                new Class<?>[] { ClassFileTransformer.class });
        ADD_TRANSFORMER.setAccessible(true);
        ADD_TRANSFORMER.invoke(delegatingTransformer, transformer);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:org.impalaframework.extension.mvc.annotation.collector.BaseArgumentCollectorTest.java

protected MethodParameter getMethodParameter(Class<?> clazz, String name, Class<?> paramType) {
    Class<?>[] paramTypes = new Class[] { paramType };
    Method method = ReflectionUtils.findMethod(clazz, name, paramTypes);
    return new MethodParameter(method, 0);
}

From source file:com.emergya.utils.DataSourceUtils.java

/**
 * Genera un nuevo data source con las propiedades
 * {@link DataSourceUtils#dataSourceProperties}
 * //from ww w .ja  v  a  2 s  .  co  m
 * @return {@link BasicDataSource}
 */
public DataSource getDataSource() {
    DataSource dataSource = new BasicDataSource();

    // Se escriben las propiedades por reflexion
    for (Object key : dataSourceProperties.keySet()) {
        if (key instanceof String) {
            try {
                String property = (String) key;
                String setter = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
                Method setterMethod = ReflectionUtils.findMethod(BasicDataSource.class, setter, String.class);
                ReflectionUtils.makeAccessible(setterMethod);
                ReflectionUtils.invokeMethod(setterMethod, dataSource,
                        dataSourceProperties.getProperty(property));
            } catch (Exception e) {
                // Error al poner la propiedad
            }
        }
    }

    return dataSource;
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java

public DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl(final Class<T> domainType) {
    super(domainType);
    this.hashAndRangeKeyMethodExtractor = new DynamoDBHashAndRangeKeyMethodExtractorImpl<T>(getJavaType());
    ReflectionUtils.doWithMethods(domainType, new MethodCallback() {
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBHashKey.class) != null) {
                String setterMethodName = toSetterMethodNameFromAccessorMethod(method);
                if (setterMethodName != null) {
                    hashKeySetterMethod = ReflectionUtils.findMethod(domainType, setterMethodName,
                            method.getReturnType());
                }// www. ja v  a2  s  . co m
            }
        }
    });
    ReflectionUtils.doWithFields(domainType, new FieldCallback() {
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBHashKey.class) != null) {

                hashKeyField = ReflectionUtils.findField(domainType, field.getName());

            }
        }
    });
    Assert.isTrue(hashKeySetterMethod != null || hashKeyField != null,
            "Unable to find hash key field or setter method on " + domainType + "!");
    Assert.isTrue(hashKeySetterMethod == null || hashKeyField == null,
            "Found both hash key field and setter method on " + domainType + "!");

}

From source file:com.iisigroup.cap.model.GenericBean.java

/**
 * set/* w w w. ja  va2 s  .c o  m*/
 * 
 * @param <T>
 *            T extends GenericBean
 * @param field
 *            ?id
 * @param value
 *            ?
 * @return T <T>
 */
@SuppressWarnings("unchecked")
public <T> T set(String field, Object value) {
    if (CapString.isEmpty(field)) {
        return (T) this;
    }
    try {
        Field f = ReflectionUtils.findField(getClass(), field);
        if (f != null) {
            String setter = new StringBuffer("set").append(String.valueOf(f.getName().charAt(0)).toUpperCase())
                    .append(f.getName().substring(1)).toString();
            Method method = ReflectionUtils.findMethod(this.getClass(), setter, new Class[] { f.getType() });
            if (method != null) {
                method.invoke(this, value);
            }
        }
    } catch (Exception e) {
        throw new CapException(
                new StringBuffer("field:").append(field).append(" ").append(e.getMessage()).toString(), e,
                getClass());
    }
    return (T) this;
}