Example usage for org.springframework.util ReflectionUtils doWithMethods

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

Introduction

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

Prototype

public static void doWithMethods(Class<?> clazz, MethodCallback mc, @Nullable MethodFilter mf) 

Source Link

Document

Perform the given callback operation on all matching methods of the given class and superclasses (or given interface and super-interfaces).

Usage

From source file:org.craftercms.commons.ebus.config.EBusBeanAutoConfiguration.java

private static Set<Method> findHandlerMethods(final Class<?> handlerType,
        final ReflectionUtils.MethodFilter listenerMethodFilter) {

    final Set<Method> handlerMethods = new LinkedHashSet<Method>();

    if (handlerType == null) {
        return handlerMethods;
    }//from  w  w w.ja va 2 s.  c  o m

    Set<Class<?>> handlerTypes = new LinkedHashSet<Class<?>>();
    Class<?> specifiedHandlerType = null;
    if (!Proxy.isProxyClass(handlerType)) {
        handlerTypes.add(handlerType);
        specifiedHandlerType = handlerType;
    }
    handlerTypes.addAll(Arrays.asList(handlerType.getInterfaces()));
    for (Class<?> currentHandlerType : handlerTypes) {
        final Class<?> targetClass = (specifiedHandlerType != null ? specifiedHandlerType : currentHandlerType);
        ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() {
            @Override
            public void doWith(final Method method) throws IllegalArgumentException, IllegalAccessException {
                Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
                Method bridgeMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
                if (listenerMethodFilter.matches(specificMethod)
                        && (bridgeMethod == specificMethod || !listenerMethodFilter.matches(bridgeMethod))) {
                    handlerMethods.add(specificMethod);
                }
            }
        }, ReflectionUtils.USER_DECLARED_METHODS);
    }

    return handlerMethods;
}

From source file:py.una.pol.karaku.log.LogPostProcessor.java

/**
 * Revisa todos los mtodos o campos que tengan la anotacin {@link Log} y
 * le asigna el valor el Log del bean en cuestin.
 * /*from w ww .j a v a 2s.  c om*/
 * <br />
 * 
 * {@inheritDoc}
 * 
 * @param bean
 *            bean a procesar
 * @param beanName
 *            nombre del bean
 * @return el mismo bean
 * @throws BeansException
 *             nunca
 */
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) {

    ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {

        @Override
        public void doWith(Field field) throws IllegalAccessException {

            if (!Modifier.isFinal(field.getModifiers())) {
                field.setAccessible(true);
                Log log = field.getAnnotation(Log.class);
                field.set(bean, getLogger(bean, log));
            }
        }

    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {

            return field.getAnnotation(Log.class) != null;
        }
    });

    ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalAccessException {

            Log log = method.getAnnotation(Log.class);
            try {
                method.invoke(bean, getLogger(bean, log));
            } catch (InvocationTargetException e) {
                LOGGER.warn("Error extracting proxy object from {}", bean.getClass().getName(), e);
            }
        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {

            return method.getAnnotation(Log.class) != null;

        }
    });

    return bean;

}

From source file:com.joshlong.activiti.coordinator.aop.ActivitiStateAnnotationBeanPostProcessor.java

public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    // first sift through and get all the methods
    // then get all the annotations
    // then build the metadata and register the metadata
    final Class<?> targetClass = AopUtils.getTargetClass(bean);
    final ActivitiComponent component = targetClass.getAnnotation(ActivitiComponent.class);

    ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
        @SuppressWarnings("unchecked")
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            ActivitiState activitiState = AnnotationUtils.getAnnotation(method, ActivitiState.class);

            String processName = component.processKey();

            if (StringUtils.hasText(activitiState.processName())) {
                processName = activitiState.processName();
            }// ww w.ja v a2 s .  c  o  m

            String stateName = activitiState.stateName();

            if (!StringUtils.hasText(stateName)) {
                stateName = activitiState.value();
            }

            Assert.notNull(stateName, "You must provide a stateName!");

            Map<Integer, String> vars = new HashMap<Integer, String>();
            Annotation[][] paramAnnotationsArray = method.getParameterAnnotations();

            int ctr = 0;
            int pvMapIndex = -1;
            int procIdIndex = -1;

            for (Annotation[] paramAnnotations : paramAnnotationsArray) {
                ctr += 1;

                for (Annotation pa : paramAnnotations) {
                    if (pa instanceof ProcessVariable) {
                        ProcessVariable pv = (ProcessVariable) pa;
                        String pvName = pv.value();
                        vars.put(ctr, pvName);
                    } else if (pa instanceof ProcessVariables) {
                        pvMapIndex = ctr;
                    } else if (pa instanceof ProcessId) {
                        procIdIndex = ctr;
                    }
                }
            }

            ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method,
                    bean, stateName, beanName, pvMapIndex, procIdIndex, processName);
            registry.registerActivitiStateHandler(registration);
        }
    }, new ReflectionUtils.MethodFilter() {
        public boolean matches(Method method) {
            return null != AnnotationUtils.getAnnotation(method, ActivitiState.class);
        }
    });

    return bean;
}

From source file:org.vbossica.springbox.annotation.AnnotatedMethodResolver.java

/**
 * Traverses the {@code bean} in search for annotated methods. Calls the
 * {@link #doWithAnnotatedMethod(String, Object, Method, Annotation)} for every method found.
 *
 * @param beanName the name of the Spring bean
 * @param bean the Spring bean itself//w w  w .j  ava 2 s. c om
 * @see #doWithAnnotatedMethod(String, Object, java.lang.reflect.Method, java.lang.annotation.Annotation)
 */
public void traverse(final String beanName, final Object bean) {
    logger.info("traversing bean " + beanName);

    Class<?> handlerType = bean.getClass();

    Class<?>[] handlerTypes = Proxy.isProxyClass(handlerType) ? handlerType.getInterfaces()
            : new Class<?>[] { handlerType };
    for (final Class<?> currentHandlerType : handlerTypes) {
        ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() {
            public void doWith(Method method) {
                Method specificMethod = ClassUtils.getMostSpecificMethod(method, currentHandlerType);
                A annotation = AnnotationUtils.findAnnotation(method, annotationClass);
                if (annotation != null) {
                    doWithAnnotatedMethod(beanName, bean, specificMethod, annotation);
                }
            }
        }, ReflectionUtils.NON_BRIDGED_METHODS);
    }
}

From source file:com.reactivetechnologies.platform.rest.depre.RequestDispatchers.java

private void addAnnotatedClass(Class<?> restletClass) throws InstantiationException, IllegalAccessException {
    final JAXRSInstanceMetadata proxy = new JAXRSInstanceMetadata(restletClass.newInstance());
    if (restletClass.isAnnotationPresent(Path.class)) {
        String rootUri = restletClass.getAnnotation(Path.class).value();
        proxy.setRootUri(rootUri);/*  w w  w . ja  va  2 s.  c  o  m*/
    }
    ReflectionUtils.doWithMethods(restletClass, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            String subUri = "";
            if (method.isAnnotationPresent(Path.class)) {
                subUri = method.getAnnotation(Path.class).value();
            }
            if (method.isAnnotationPresent(GET.class)) {
                MethodDetail m = new MethodDetail(method);
                Annotation[][] mAnnots = method.getParameterAnnotations();
                int i = 0;
                for (Annotation[] annots : mAnnots) {
                    for (Annotation annot : annots) {
                        if (annot.annotationType() == QueryParam.class) {
                            m.setQueryParam(i, ((QueryParam) annot).value());
                        }
                    }
                    i++;
                }
                proxy.addGetMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(POST.class)) {
                MethodDetail m = new MethodDetail(method);
                Annotation[][] mAnnots = method.getParameterAnnotations();
                int i = 0;
                for (Annotation[] annots : mAnnots) {
                    for (Annotation annot : annots) {
                        if (annot.annotationType() == QueryParam.class) {
                            m.setQueryParam(i, ((QueryParam) annot).value());
                        }
                    }
                    i++;
                }
                proxy.addPostMethod(proxy.getRootUri() + subUri, m);
            }

        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return (method.isAnnotationPresent(GET.class) || method.isAnnotationPresent(POST.class));
        }
    });

    allClasses.add(proxy);
}

From source file:io.dyn.core.handler.AnnotationHandlerMethodResolver.java

@Override
public Map<Object, HandlerMethod> resolve(Class<?> aClass, Object... args) {
    final Map<Object, HandlerMethod> handlerMethods = new HashMap<>();
    //log.debug("Finding handler methods in %s", aClass);
    Class<?> clazz = aClass;
    while (null != clazz && clazz != Object.class) {
        ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
            @Override// w  w w .j a v  a  2 s.c om
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

                Class<?>[] paramTypes = method.getParameterTypes();
                String[] paramNames = PARAMETER_NAME_DISCOVERER.getParameterNames(method);
                HandlerMethodArgument[] handlerMethodArgs = new HandlerMethodArgument[paramTypes.length];
                Annotation[][] paramAnnos = method.getParameterAnnotations();
                Expression[] valueExpressions = new Expression[paramTypes.length];
                for (int i = 0; i < paramTypes.length; i++) {
                    String paramName = (null != paramNames ? paramNames[i] : "arg" + i);
                    if (paramAnnos[i].length > 0) {
                        for (int j = 0; j < paramAnnos[i].length; j++) {
                            if (paramAnnos[i][j] instanceof Value) {
                                valueExpressions[i] = SpelExpression.DEFAULT_PARSER
                                        .parseExpression(((Value) paramAnnos[i][j]).value());
                                break;
                            }
                        }
                    }
                    handlerMethodArgs[i] = new HandlerMethodArgument(i, paramName, paramTypes[i],
                            valueExpressions[i]);
                }

                Guard guard = null;
                When when = Handlers.find(When.class, method);
                if (null != when) {
                    guard = new Guard(SpelExpression.DEFAULT_PARSER.parseExpression(when.value()));
                }

                On on = Handlers.find(On.class, method);
                String eventName = Handlers.findEventName(method);
                if (null != eventName) {
                    Object key = eventName;
                    if (eventName.contains("#{")) {
                        key = SpelExpression.DEFAULT_PARSER.parseExpression(eventName,
                                ParserContext.TEMPLATE_EXPRESSION);
                    }
                    handlerMethods.put(key, new HandlerMethod(method, handlerMethodArgs, guard));

                }
            }
        }, Handlers.USER_METHODS);
        clazz = clazz.getSuperclass();
    }
    return (handlerMethods.size() > 0 ? handlerMethods : null);
}

From source file:org.activiti.spring.components.aop.ActivitiStateAnnotationBeanPostProcessor.java

public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    // first sift through and get all the methods
    // then get all the annotations
    // then build the metadata and register the metadata
    final Class<?> targetClass = AopUtils.getTargetClass(bean);
    final org.activiti.spring.annotations.ActivitiComponent component = targetClass
            .getAnnotation(org.activiti.spring.annotations.ActivitiComponent.class);

    ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
        @SuppressWarnings("unchecked")
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            State state = AnnotationUtils.getAnnotation(method, State.class);

            String processName = component.processKey();

            if (StringUtils.hasText(state.process())) {
                processName = state.process();
            }/*from w w w. java  2s .co  m*/

            String stateName = state.state();

            if (!StringUtils.hasText(stateName)) {
                stateName = state.value();
            }

            Assert.notNull(stateName, "You must provide a stateName!");

            Map<Integer, String> vars = new HashMap<Integer, String>();
            Annotation[][] paramAnnotationsArray = method.getParameterAnnotations();

            int ctr = 0;
            int pvMapIndex = -1;
            int procIdIndex = -1;

            for (Annotation[] paramAnnotations : paramAnnotationsArray) {
                ctr += 1;

                for (Annotation pa : paramAnnotations) {
                    if (pa instanceof ProcessVariable) {
                        ProcessVariable pv = (ProcessVariable) pa;
                        String pvName = pv.value();
                        vars.put(ctr, pvName);
                    } else if (pa instanceof ProcessVariables) {
                        pvMapIndex = ctr;
                    } else if (pa instanceof ProcessId) {
                        procIdIndex = ctr;
                    }
                }
            }

            ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method,
                    bean, stateName, beanName, pvMapIndex, procIdIndex, processName);
            registry.registerActivitiStateHandler(registration);
        }
    }, new ReflectionUtils.MethodFilter() {
        public boolean matches(Method method) {
            return null != AnnotationUtils.getAnnotation(method, State.class);
        }
    });

    return bean;
}

From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java

/**
 * <p>Reads class' metadata and returns a {@link XmlEventsPattern pattern of XML events} which may be used to marshal
 * an object of the analyzed class.<?p>
 * //from   w ww .  ja v a2s  .  com
 * @return
 */
public TypedPattern<T> analyze() {
    TypedPattern<T> result = this.patternRegistry.findPatternByClass(this.clazz);

    if (result != null)
        return result;

    log.trace("Analyzing {} class with {} type name", this.clazz.getName(), this.typeName);

    // analyze fields
    ReflectionUtils.doWithFields(this.clazz, this, new FieldFilter() {
        @Override
        public boolean matches(Field field) {
            return !Modifier.isStatic(field.getModifiers());
        }
    });

    // analyze get/set methods - even private ones!
    ReflectionUtils.doWithMethods(this.clazz, this, new MethodFilter() {
        @Override
        public boolean matches(Method method) {
            boolean match = true;
            // is it getter?
            match &= method.getName().startsWith("get");
            match &= method.getParameterTypes().length == 0;
            match &= method.getReturnType() != Void.class;
            // is there a setter?
            if (match) {
                Method setter = ReflectionUtils.findMethod(clazz, method.getName().replaceFirst("^get", "set"),
                        method.getReturnType());
                // TODO: maybe allow non-void returning setters as Spring-Framework already does? Now: yes
                match = setter != null || Collection.class.isAssignableFrom(method.getReturnType());
            }

            return match;
        }
    });

    if (this.valueMetadata != null && this.childElementMetadata.size() == 0
            && this.childAttributeMetadata.size() == 0) {
        // we have a special case, where Java class becomes simpleType:
        //  - formatting the analyzed class is really formatting the value
        //  - the type information of the analyzed class is not changed!
        log.trace("Changing {} class' pattern to SimpleContentPattern", this.clazz.getName());

        SimpleContentPattern<T> valuePattern = SimpleContentPattern.newValuePattern(this.typeName, this.clazz);
        SimpleContentPattern<?> simpleTypePattern = (SimpleContentPattern<?>) this.valueMetadata.getPattern();
        valuePattern.setFormatter(
                PeelingFormatter.newPeelingFormatter(this.valueMetadata, simpleTypePattern.getFormatter()));
        result = valuePattern;
    } else {
        if (this.valueMetadata != null && this.childElementMetadata.size() > 0) {
            throw new RuntimeException("TODO: can't mix @XmlValue and @XmlElements");
        }

        // we have complex type (possibly with simpleContent, when there's @XmlValue + one or more @XmlAttributes)
        // @XmlAttributes first. then @XmlElements
        this.childAttributeMetadata.addAll(this.childElementMetadata);
        if (this.valueMetadata != null)
            this.childAttributeMetadata.add(this.valueMetadata);

        result = ComplexTypePattern.newContentModelPattern(this.typeName, this.clazz,
                this.childAttributeMetadata);
    }

    if (log.isTraceEnabled())
        log.trace("-> Class {} was mapped to {} with {} XSD type", this.clazz.getName(), result, this.typeName);

    return result;
}

From source file:com.reactivetechnologies.platform.rest.WebbitRestServerBean.java

/**
 * //from  ww w .j  a v a 2 s .  c  o  m
 * @param restletClass
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
static JAXRSInstanceMetadata scanJaxRsClass(Class<?> restletClass)
        throws InstantiationException, IllegalAccessException {
    final JAXRSInstanceMetadata proxy = new JAXRSInstanceMetadata(restletClass.newInstance());
    if (restletClass.isAnnotationPresent(Path.class)) {
        String rootUri = restletClass.getAnnotation(Path.class).value();
        if (rootUri == null)
            rootUri = "";
        proxy.setRootUri(rootUri);
    }
    ReflectionUtils.doWithMethods(restletClass, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            String subUri = "";
            if (method.isAnnotationPresent(Path.class)) {
                subUri = method.getAnnotation(Path.class).value();
            }
            if (method.isAnnotationPresent(GET.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addGetMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(POST.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addPostMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(DELETE.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addDelMethod(proxy.getRootUri() + subUri, m);
            }

        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return (method.isAnnotationPresent(GET.class) || method.isAnnotationPresent(POST.class)
                    || method.isAnnotationPresent(DELETE.class));
        }
    });

    return proxy;
}

From source file:org.lexevs.dao.database.utility.DaoUtility.java

/**
 * Insert into mappings./*  w  w  w  . j ava  2 s . com*/
 * 
 * @param mappings the mappings
 * @param uriMap the uri map
 */
public static List<URIMap> getAllURIMappings(final Mappings mappings) {
    final String getPrefix = "get";
    final String getSuffix = "AsReference";

    final List<URIMap> uriMapList = new ArrayList<URIMap>();

    ReflectionUtils.doWithMethods(mappings.getClass(), new MethodCallback() {

        @SuppressWarnings("unchecked")
        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            try {
                List<URIMap> list = (List<URIMap>) method.invoke(mappings);
                uriMapList.addAll(list);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }

    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return method.getName().startsWith(getPrefix) && method.getName().endsWith(getSuffix);
        }

    });

    return uriMapList;
}