Example usage for org.springframework.util ClassUtils getMethodIfAvailable

List of usage examples for org.springframework.util ClassUtils getMethodIfAvailable

Introduction

In this page you can find the example usage for org.springframework.util ClassUtils getMethodIfAvailable.

Prototype

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

Source Link

Document

Determine whether the given class has a public method with the given signature, and return it if available (else return null ).

Usage

From source file:de.otto.jsonhome.generator.MethodHelper.java

private static Method methodFromSuperclass(final Method method) {
    final Class<?> superclass = method.getDeclaringClass().getSuperclass();
    if (superclass != null) {
        return ClassUtils.getMethodIfAvailable(superclass, method.getName(), method.getParameterTypes());
    }/*from  w ww. j a  va2 s . c  om*/
    return null;
}

From source file:org.focusns.common.validation.ValidationHelper.java

/**
 * ??//  ww w.  j ava 2s  .co  m
 * 
 * @param constraintDescriptor
 * @return
 */
private static List<String> getConstraintParams(ConstraintDescriptor<?> constraintDescriptor) {
    Annotation constraintInstance = constraintDescriptor.getAnnotation();
    Class<?> constraintClass = constraintDescriptor.getAnnotation().annotationType();
    //
    List<String> params = new ArrayList<String>();
    //
    Method valueMethod = ClassUtils.getMethodIfAvailable(constraintClass, "value", (Class<?>[]) null);
    if (valueMethod != null) {
        String value = String.valueOf(ReflectionUtils.invokeMethod(valueMethod, constraintInstance));
        params.add("value:" + value);
    }
    Map<String, Object> annotationAttrs = AnnotationUtils.getAnnotationAttributes(constraintInstance);
    for (String key : annotationAttrs.keySet()) {
        if ("message".equals(key) || "payload".equals(key)) {
            continue;
        }
        //
        String value = "";
        if ("groups".equals(key)) {
            List<String> groupNames = new ArrayList<String>();
            Class[] groupClasses = (Class[]) annotationAttrs.get(key);
            for (Class groupClass : groupClasses) {
                groupNames.add(groupClass.getName());
            }
            value = StringUtils.collectionToDelimitedString(groupNames, "|");
        } else {
            value = String.valueOf(annotationAttrs.get(key));
        }
        //
        if (StringUtils.hasText(value)) {
            params.add(key + ":" + "'" + value + "'");
        }
    }
    //
    return params;
}

From source file:net.alpha.velocity.spring.web.VelocityToolboxView.java

/**
 * Overridden to check for the ViewContext interface which is part of the
 * view package of Velocity Tools. This requires a special Velocity context,
 * like ChainedContext as set up by {@link #createVelocityContext} in this class.
 *//*from ww  w.j av  a  2  s . c om*/
@Override
protected void initTool(Object tool, Context velocityContext) throws Exception {
    // Velocity Tools 1.3: a class-level "init(Object)" method.
    Method initMethod = ClassUtils.getMethodIfAvailable(tool.getClass(), "init", Object.class);
    if (initMethod != null) {
        ReflectionUtils.invokeMethod(initMethod, tool, velocityContext);
    }
}

From source file:org.jdal.dao.hibernate.HibernateDao.java

/**
 * Create a Criteria from filter. If filter is a entity class instance, 
 * return a Criteria with a Example Criterion applied.
 * If not try four options in order:/*from  w ww.  j a v a 2s  .co m*/
 * 
 *    1. if there are a filter with name filter.getName() enable it and return criteria
 *  2. if there are a criteria builder with name filter.getName() use it to create Critera.
 *  4. if there are a method named createCritera + filter.getName() invoke it to create Criteria
 *  5. Return a Criteria for this entity class without Criterion applied.
 * 
 * @param filter the filter
 * @return a new Criteria 
 */
protected Criteria getCriteria(Page<?> page) {
    Criteria executableCriteria = getSession().createCriteria(getEntityClass());
    Object filter = page.getFilter();
    // apply filter, if any
    if (filter != null) {
        if (ClassUtils.isAssignable(getEntityClass(), filter.getClass())) {
            // try a findByExample...
            executableCriteria.add(Example.create(getEntityClass()));
        } else if (filter instanceof Filter) {
            Filter f = (Filter) filter;

            if (!enableFilter(f)) {
                if (log.isDebugEnabled())
                    log.debug("No hibernate filter found with name: " + f.getFilterName()
                            + ", try criteria builder.");
                // if no filter, try criteria builder
                if (criteriaBuilderMap.containsKey(f.getFilterName())) {
                    CriteriaBuilder cb = criteriaBuilderMap.get(f.getFilterName());
                    if (log.isDebugEnabled())
                        log.debug("Found criteria builder with name: " + f.getFilterName()
                                + " - criteria builder class: " + cb.getClass().getSimpleName());
                    executableCriteria = cb.build(executableCriteria, f);
                }
                // if no criteria builder try subclass method
                else if (ClassUtils.hasMethod(getClass(), "createCriteria" + f.getFilterName(),
                        new Class[] { Criteria.class })) {
                    Method method = ClassUtils.getMethodIfAvailable(getClass(),
                            "createCriteria" + f.getFilterName(), new Class[] { Criteria.class });
                    if (method != null) {
                        try {
                            executableCriteria = (Criteria) method.invoke(this, executableCriteria);
                        } catch (Exception e) {
                            log.error(e);
                        }
                    }
                }
            }
        } else {
            log.warn("Cannot manage filter of type: " + filter.getClass());
        }
    }

    return executableCriteria;
}

From source file:net.yasion.common.core.bean.wrapper.GenericTypeAwarePropertyDescriptor.java

public GenericTypeAwarePropertyDescriptor(Class<?> beanClass, String propertyName, Method readMethod,
        Method writeMethod, Class<?> propertyEditorClass) throws IntrospectionException {

    super(propertyName, null, null);

    if (beanClass == null) {
        throw new IntrospectionException("Bean class must not be null");
    }/*from   www. j a  v  a2  s  .co  m*/
    this.beanClass = beanClass;

    Method readMethodToUse = BridgeMethodResolver.findBridgedMethod(readMethod);
    Method writeMethodToUse = BridgeMethodResolver.findBridgedMethod(writeMethod);
    if (writeMethodToUse == null && readMethodToUse != null) {
        // Fallback: Original JavaBeans introspection might not have found matching setter
        // method due to lack of bridge method resolution, in case of the getter using a
        // covariant return type whereas the setter is defined for the concrete property type.
        Method candidate = ClassUtils.getMethodIfAvailable(this.beanClass,
                "set" + StringUtils.capitalize(getName()), (Class<?>[]) null);
        if (candidate != null && candidate.getParameterTypes().length == 1) {
            writeMethodToUse = candidate;
        }
    }
    this.readMethod = readMethodToUse;
    this.writeMethod = writeMethodToUse;

    if (this.writeMethod != null) {
        if (this.readMethod == null) {
            // Write method not matched against read method: potentially ambiguous through
            // several overloaded variants, in which case an arbitrary winner has been chosen
            // by the JDK's JavaBeans Introspector...
            Set<Method> ambiguousCandidates = new HashSet<Method>();
            for (Method method : beanClass.getMethods()) {
                if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse)
                        && !method.isBridge()) {
                    ambiguousCandidates.add(method);
                }
            }
            if (!ambiguousCandidates.isEmpty()) {
                this.ambiguousWriteMethods = ambiguousCandidates;
            }
        }
        this.writeMethodParameter = new MethodParameter(this.writeMethod, 0);
        GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
    }

    if (this.readMethod != null) {
        this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
    } else if (this.writeMethodParameter != null) {
        this.propertyType = this.writeMethodParameter.getParameterType();
    }

    this.propertyEditorClass = propertyEditorClass;
}

From source file:org.hopen.framework.rewrite.GenericTypeAwarePropertyDescriptor.java

public GenericTypeAwarePropertyDescriptor(Class beanClass, String propertyName, Method readMethod,
        Method writeMethod, Class propertyEditorClass) throws IntrospectionException {

    super(propertyName, null, null);
    this.beanClass = beanClass;
    this.propertyEditorClass = propertyEditorClass;

    Method readMethodToUse = BridgeMethodResolver.findBridgedMethod(readMethod);
    Method writeMethodToUse = BridgeMethodResolver.findBridgedMethod(writeMethod);
    if (writeMethodToUse == null && readMethodToUse != null) {
        // Fallback: Original JavaBeans introspection might not have found matching setter
        // method due to lack of bridge method resolution, in case of the getter using a
        // covariant return type whereas the setter is defined for the concrete property type.
        writeMethodToUse = ClassUtils.getMethodIfAvailable(this.beanClass,
                "set" + StringUtils.capitalize(getName()), readMethodToUse.getReturnType());
    }/*  w w w .j ava2s .  com*/
    this.readMethod = readMethodToUse;
    this.writeMethod = writeMethodToUse;

    if (this.writeMethod != null && this.readMethod == null) {
        // Write method not matched against read method: potentially ambiguous through
        // several overloaded variants, in which case an arbitrary winner has been chosen
        // by the JDK's JavaBeans Introspector...
        Set<Method> ambiguousCandidates = new HashSet<Method>();
        for (Method method : beanClass.getMethods()) {
            if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse)
                    && !method.isBridge()) {
                ambiguousCandidates.add(method);
            }
        }
        if (!ambiguousCandidates.isEmpty()) {
            this.ambiguousWriteMethods = ambiguousCandidates;
        }
    }
}

From source file:org.springframework.beans.GenericTypeAwarePropertyDescriptor.java

public GenericTypeAwarePropertyDescriptor(Class<?> beanClass, String propertyName, @Nullable Method readMethod,
        @Nullable Method writeMethod, Class<?> propertyEditorClass) throws IntrospectionException {

    super(propertyName, null, null);
    this.beanClass = beanClass;

    Method readMethodToUse = (readMethod != null ? BridgeMethodResolver.findBridgedMethod(readMethod) : null);
    Method writeMethodToUse = (writeMethod != null ? BridgeMethodResolver.findBridgedMethod(writeMethod)
            : null);/* w w w  .  jav  a2  s .  c  om*/
    if (writeMethodToUse == null && readMethodToUse != null) {
        // Fallback: Original JavaBeans introspection might not have found matching setter
        // method due to lack of bridge method resolution, in case of the getter using a
        // covariant return type whereas the setter is defined for the concrete property type.
        Method candidate = ClassUtils.getMethodIfAvailable(this.beanClass,
                "set" + StringUtils.capitalize(getName()), (Class<?>[]) null);
        if (candidate != null && candidate.getParameterCount() == 1) {
            writeMethodToUse = candidate;
        }
    }
    this.readMethod = readMethodToUse;
    this.writeMethod = writeMethodToUse;

    if (this.writeMethod != null) {
        if (this.readMethod == null) {
            // Write method not matched against read method: potentially ambiguous through
            // several overloaded variants, in which case an arbitrary winner has been chosen
            // by the JDK's JavaBeans Introspector...
            Set<Method> ambiguousCandidates = new HashSet<>();
            for (Method method : beanClass.getMethods()) {
                if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse)
                        && !method.isBridge()
                        && method.getParameterCount() == writeMethodToUse.getParameterCount()) {
                    ambiguousCandidates.add(method);
                }
            }
            if (!ambiguousCandidates.isEmpty()) {
                this.ambiguousWriteMethods = ambiguousCandidates;
            }
        }
        this.writeMethodParameter = new MethodParameter(this.writeMethod, 0);
        GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
    }

    if (this.readMethod != null) {
        this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
    } else if (this.writeMethodParameter != null) {
        this.propertyType = this.writeMethodParameter.getParameterType();
    }

    this.propertyEditorClass = propertyEditorClass;
}

From source file:org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver.java

/**
 * Create a new SimpleLoadTimeWeaver for the given class loader.
 * @param classLoader the {@code ClassLoader} to delegate to for
 * weaving (<i>must</i> support the required weaving methods).
 * @throws IllegalStateException if the supplied {@code ClassLoader}
 * does not support the required weaving methods
 *//*from   ww  w  .j ava 2  s  .c  o m*/
public ReflectiveLoadTimeWeaver(@Nullable ClassLoader classLoader) {
    Assert.notNull(classLoader, "ClassLoader must not be null");
    this.classLoader = classLoader;

    Method addTransformerMethod = ClassUtils.getMethodIfAvailable(this.classLoader.getClass(),
            ADD_TRANSFORMER_METHOD_NAME, ClassFileTransformer.class);
    if (addTransformerMethod == null) {
        throw new IllegalStateException("ClassLoader [" + classLoader.getClass().getName()
                + "] does NOT provide an " + "'addTransformer(ClassFileTransformer)' method.");
    }
    this.addTransformerMethod = addTransformerMethod;

    Method getThrowawayClassLoaderMethod = ClassUtils.getMethodIfAvailable(this.classLoader.getClass(),
            GET_THROWAWAY_CLASS_LOADER_METHOD_NAME);
    // getThrowawayClassLoader method is optional
    if (getThrowawayClassLoaderMethod == null) {
        if (logger.isInfoEnabled()) {
            logger.info("The ClassLoader [" + classLoader.getClass().getName() + "] does NOT provide a "
                    + "'getThrowawayClassLoader()' method; SimpleThrowawayClassLoader will be used instead.");
        }
    }
    this.getThrowawayClassLoaderMethod = getThrowawayClassLoaderMethod;
}