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) 

Source Link

Document

Perform the given callback operation on all matching methods of the given class and superclasses.

Usage

From source file:org.openspaces.events.AbstractEventListenerContainer.java

private void initializeExceptionHandler() {
    if (exceptionHandler == null && getActualEventListener() != null) {
        final AtomicReference<Method> ref = new AtomicReference<Method>();
        ReflectionUtils.doWithMethods(AopUtils.getTargetClass(getActualEventListener()),
                new ReflectionUtils.MethodCallback() {
                    public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                        if (method.isAnnotationPresent(ExceptionHandler.class)) {
                            ref.set(method);
                        }//  w  w  w  . ja va2 s  . c  om
                    }
                });
        if (ref.get() != null) {
            ref.get().setAccessible(true);
            try {
                setExceptionHandler((EventExceptionHandler) ref.get().invoke(getActualEventListener()));
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "Failed to set EventExceptionHandler from method [" + ref.get().getName() + "]", e);
            }
        }
    }
}

From source file:org.openspaces.pu.container.ProcessingUnitContainerContextBeanPostProcessor.java

private void processMetrics(final Object bean, final String beanName) {
    final AtomicReference<BeanMetricManager> metricManagerHolder = new AtomicReference<BeanMetricManager>();
    ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
        @Override//from   w ww.  j a va  2  s  .c o  m
        public void doWith(Method method) {
            ServiceMetric annotation = method.getAnnotation(ServiceMetric.class);
            if (annotation != null) {
                Metric metric = getMetricFromMethod(method, bean);
                if (metric != null) {
                    if (logger.isDebugEnabled())
                        logger.debug("Registering custom metric " + annotation.name());
                    if (metricManagerHolder.get() == null)
                        metricManagerHolder
                                .set(processingUnitContainerContext.createBeanMetricManager(beanName));
                    metricManagerHolder.get().register(annotation.name(), metric);
                }
            }
        }
    });
}

From source file:org.springbyexample.mvc.method.annotation.ServiceHandlerMapping.java

/**
 * Process and setup any converter handlers if one is configured on <code>RestRequestResource</code>.
 *///from  w ww .ja  v a2 s . c o m
private void processConverters(RestRequestResource restRequestResource, RequestMappingInfo mapping,
        Method serviceMethod) {
    ApplicationContext ctx = getApplicationContext();
    Class<?> converterClass = (restRequestResource != null ? restRequestResource.converter() : null);

    if (converterClass != null && converterClass != ServiceValueConstants.DEFAULT_CONVERTER_CLASS) {
        @SuppressWarnings("rawtypes")
        ListConverter converter = (ListConverter) ctx.getBean(converterClass);

        String[] pathPatterns = mapping.getPatternsCondition().getPatterns()
                .toArray(ArrayUtils.EMPTY_STRING_ARRAY);

        String methodSuffix = StringUtils.capitalize(converterHandlerInfo.getPropertyName());
        String getterMethodName = "get" + methodSuffix;
        final String setterMethodName = "set" + methodSuffix;

        final Class<?> returnTypeClass = serviceMethod.getReturnType();
        Method getResultsMethod = ReflectionUtils.findMethod(returnTypeClass, getterMethodName);
        final Class<?> resultReturnTypeClass = getResultsMethod.getReturnType();
        Method setResultsMethod = ReflectionUtils.findMethod(returnTypeClass, setterMethodName,
                resultReturnTypeClass);
        final AtomicReference<Method> altSetResultsMethod = new AtomicReference<Method>();

        // issue with ReflectionUtils, setterResultsMethod sometimes null from the command line (not getter?)
        if (setResultsMethod == null) {
            ReflectionUtils.doWithMethods(returnTypeClass, new MethodCallback() {
                @Override
                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    if (setterMethodName.equals(method.getName())) {
                        altSetResultsMethod.set(method);
                        logger.debug(
                                "Unable to use ReflectionUtils to find setter. returnTypeClass={}  method={} resultReturnTypeClass={}",
                                new Object[] { returnTypeClass, method, resultReturnTypeClass });
                    }
                }
            });
        }

        HandlerInterceptor interceptor = new ConverterHandlerInterceptor(converter, returnTypeClass,
                getResultsMethod, (setResultsMethod != null ? setResultsMethod : altSetResultsMethod.get()));

        MappedInterceptor mappedInterceptor = new MappedInterceptor(pathPatterns, interceptor);
        setInterceptors(new Object[] { mappedInterceptor });

        logger.info("Registered converter post handler for {} with {}.", pathPatterns,
                converterClass.getCanonicalName());
    }
}

From source file:org.springbyexample.util.log.LoggerBeanPostProcessor.java

/**
 * Instantiates bean specific loggers and sets them.
 *//*from w w w.  j  a v a 2s. com*/
protected void processLogger(final Object bean, final String methodName) {
    final Class<?> clazz = bean.getClass();

    ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) {
            if (method.getName().equals(methodName)) {
                try {
                    injectMethod(bean, method);
                } catch (Throwable e) {
                    throw new FatalBeanException("Problem injecting logger.  " + e.getMessage(), e);
                }
            }
        }
    });
}

From source file:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.java

@Override
@Nullable/*from ww  w .  jav a  2  s. c om*/
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
        throws BeanCreationException {

    // Let's check for lookup methods here..
    if (!this.lookupMethodsChecked.contains(beanName)) {
        try {
            ReflectionUtils.doWithMethods(beanClass, method -> {
                Lookup lookup = method.getAnnotation(Lookup.class);
                if (lookup != null) {
                    Assert.state(beanFactory != null, "No BeanFactory available");
                    LookupOverride override = new LookupOverride(method, lookup.value());
                    try {
                        RootBeanDefinition mbd = (RootBeanDefinition) beanFactory
                                .getMergedBeanDefinition(beanName);
                        mbd.getMethodOverrides().addOverride(override);
                    } catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(beanName,
                                "Cannot apply @Lookup to beans without corresponding bean definition");
                    }
                }
            });
        } catch (IllegalStateException ex) {
            throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
        }
        this.lookupMethodsChecked.add(beanName);
    }

    // Quick check on the concurrent map first, with minimal locking.
    Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    if (candidateConstructors == null) {
        // Fully synchronized resolution now...
        synchronized (this.candidateConstructorsCache) {
            candidateConstructors = this.candidateConstructorsCache.get(beanClass);
            if (candidateConstructors == null) {
                Constructor<?>[] rawCandidates;
                try {
                    rawCandidates = beanClass.getDeclaredConstructors();
                } catch (Throwable ex) {
                    throw new BeanCreationException(beanName,
                            "Resolution of declared constructors on bean Class [" + beanClass.getName()
                                    + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed",
                            ex);
                }
                List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
                Constructor<?> requiredConstructor = null;
                Constructor<?> defaultConstructor = null;
                Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
                int nonSyntheticConstructors = 0;
                for (Constructor<?> candidate : rawCandidates) {
                    if (!candidate.isSynthetic()) {
                        nonSyntheticConstructors++;
                    } else if (primaryConstructor != null) {
                        continue;
                    }
                    AnnotationAttributes ann = findAutowiredAnnotation(candidate);
                    if (ann == null) {
                        Class<?> userClass = ClassUtils.getUserClass(beanClass);
                        if (userClass != beanClass) {
                            try {
                                Constructor<?> superCtor = userClass
                                        .getDeclaredConstructor(candidate.getParameterTypes());
                                ann = findAutowiredAnnotation(superCtor);
                            } catch (NoSuchMethodException ex) {
                                // Simply proceed, no equivalent superclass constructor found...
                            }
                        }
                    }
                    if (ann != null) {
                        if (requiredConstructor != null) {
                            throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: "
                                    + candidate
                                    + ". Found constructor with 'required' Autowired annotation already: "
                                    + requiredConstructor);
                        }
                        boolean required = determineRequiredStatus(ann);
                        if (required) {
                            if (!candidates.isEmpty()) {
                                throw new BeanCreationException(beanName,
                                        "Invalid autowire-marked constructors: " + candidates
                                                + ". Found constructor with 'required' Autowired annotation: "
                                                + candidate);
                            }
                            requiredConstructor = candidate;
                        }
                        candidates.add(candidate);
                    } else if (candidate.getParameterCount() == 0) {
                        defaultConstructor = candidate;
                    }
                }
                if (!candidates.isEmpty()) {
                    // Add default constructor to list of optional constructors, as fallback.
                    if (requiredConstructor == null) {
                        if (defaultConstructor != null) {
                            candidates.add(defaultConstructor);
                        } else if (candidates.size() == 1 && logger.isWarnEnabled()) {
                            logger.warn("Inconsistent constructor declaration on bean with name '" + beanName
                                    + "': single autowire-marked constructor flagged as optional - "
                                    + "this constructor is effectively required since there is no "
                                    + "default constructor to fall back to: " + candidates.get(0));
                        }
                    }
                    candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]);
                } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
                    candidateConstructors = new Constructor<?>[] { rawCandidates[0] };
                } else if (nonSyntheticConstructors == 2 && primaryConstructor != null
                        && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor, defaultConstructor };
                } else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor };
                } else {
                    candidateConstructors = new Constructor<?>[0];
                }
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
    return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Introspect the factory method signatures on the given bean class,
 * trying to find a common {@code FactoryBean} object type declared there.
 * @param beanClass the bean class to find the factory method on
 * @param factoryMethodName the name of the factory method
 * @return the common {@code FactoryBean} object type, or {@code null} if none
 *//*from   w  ww.j  a va 2 s.  c o m*/
@Nullable
private Class<?> getTypeForFactoryBeanFromMethod(Class<?> beanClass, final String factoryMethodName) {

    /**
     * Holder used to keep a reference to a {@code Class} value.
     */
    class Holder {

        @Nullable
        Class<?> value = null;
    }

    final Holder objectType = new Holder();

    // CGLIB subclass methods hide generic parameters; look at the original user class.
    Class<?> fbClass = ClassUtils.getUserClass(beanClass);

    // Find the given factory method, taking into account that in the case of
    // @Bean methods, there may be parameters present.
    ReflectionUtils.doWithMethods(fbClass, method -> {
        if (method.getName().equals(factoryMethodName)
                && FactoryBean.class.isAssignableFrom(method.getReturnType())) {
            Class<?> currentType = GenericTypeResolver.resolveReturnTypeArgument(method, FactoryBean.class);
            if (currentType != null) {
                objectType.value = ClassUtils.determineCommonAncestor(currentType, objectType.value);
            }
        }
    });

    return (objectType.value != null && Object.class != objectType.value ? objectType.value : null);
}

From source file:org.springframework.boot.autoconfigure.condition.AbstractOnBeanCondition.java

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(annotationClass().getName(),
            true);//w w  w .  j av  a2s .c  om
    final List<String> beanClasses = collect(attributes, "value");
    final List<String> beanNames = collect(attributes, "name");

    if (beanClasses.size() == 0) {
        if (metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName())) {
            try {
                final MethodMetadata methodMetadata = (MethodMetadata) metadata;
                // We should be safe to load at this point since we are in the
                // REGISTER_BEAN phase
                Class<?> configClass = ClassUtils.forName(methodMetadata.getDeclaringClassName(),
                        context.getClassLoader());
                ReflectionUtils.doWithMethods(configClass, new MethodCallback() {
                    @Override
                    public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                        if (methodMetadata.getMethodName().equals(method.getName())) {
                            beanClasses.add(method.getReturnType().getName());
                        }
                    }
                });
            } catch (Exception ex) {
                // swallow exception and continue
            }
        }
    }

    Assert.isTrue(beanClasses.size() > 0 || beanNames.size() > 0,
            "@" + ClassUtils.getShortName(annotationClass()) + " annotations must specify at least one bean");

    return matches(context, metadata, beanClasses, beanNames);
}

From source file:org.springframework.cloud.stream.binding.BindableProxyFactory.java

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notEmpty(BindableProxyFactory.this.bindingTargetFactories,
            "'bindingTargetFactories' cannot be empty");
    ReflectionUtils.doWithMethods(this.type, new ReflectionUtils.MethodCallback() {
        @Override/*ww  w  .jav  a2s .  co m*/
        public void doWith(Method method) throws IllegalArgumentException {
            Input input = AnnotationUtils.findAnnotation(method, Input.class);
            if (input != null) {
                String name = BindingBeanDefinitionRegistryUtils.getBindingTargetName(input, method);
                Class<?> returnType = method.getReturnType();
                Object sharedBindingTarget = locateSharedBindingTarget(name, returnType);
                if (sharedBindingTarget != null) {
                    BindableProxyFactory.this.inputHolders.put(name,
                            new BoundTargetHolder(sharedBindingTarget, false));
                } else {
                    BindableProxyFactory.this.inputHolders.put(name,
                            new BoundTargetHolder(getBindingTargetFactory(returnType).createInput(name), true));
                }
            }
        }
    });
    ReflectionUtils.doWithMethods(this.type, new ReflectionUtils.MethodCallback() {
        @Override
        public void doWith(Method method) throws IllegalArgumentException {
            Output output = AnnotationUtils.findAnnotation(method, Output.class);
            if (output != null) {
                String name = BindingBeanDefinitionRegistryUtils.getBindingTargetName(output, method);
                Class<?> returnType = method.getReturnType();
                Object sharedBindingTarget = locateSharedBindingTarget(name, returnType);
                if (sharedBindingTarget != null) {
                    BindableProxyFactory.this.outputHolders.put(name,
                            new BoundTargetHolder(sharedBindingTarget, false));
                } else {
                    BindableProxyFactory.this.outputHolders.put(name, new BoundTargetHolder(
                            getBindingTargetFactory(returnType).createOutput(name), true));
                }
            }
        }
    });
}

From source file:org.springframework.data.rest.core.projection.ProxyProjectionFactory.java

/**
 * Inspects the given target type for methods with {@link Value} annotations and caches the result. Will create a
 * {@link SpelEvaluatingMethodInterceptor} if an annotation was found or return the delegate as is if not.
 * /* ww  w.j a v a2  s  .c  o m*/
 * @param source The backing source object.
 * @param projectionType the proxy target type.
 * @param delegate the root {@link MethodInterceptor}.
 * @return
 */
private MethodInterceptor getSpelMethodInterceptorIfNecessary(Object source, Class<?> projectionType,
        MethodInterceptor delegate) {

    if (!typeCache.containsKey(projectionType)) {

        AnnotationDetectionMethodCallback<Value> callback = new AnnotationDetectionMethodCallback<Value>(
                Value.class);
        ReflectionUtils.doWithMethods(projectionType, callback);

        typeCache.put(projectionType, callback.hasFoundAnnotation());
    }

    return typeCache.get(projectionType) ? new SpelEvaluatingMethodInterceptor(delegate, source, beanFactory)
            : delegate;
}

From source file:org.springframework.integration.config.annotation.MessagingAnnotationPostProcessor.java

public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    Assert.notNull(this.beanFactory, "BeanFactory must not be null");
    final Class<?> beanClass = this.getBeanClass(bean);
    if (!this.isStereotype(beanClass)) {
        // we only post-process stereotype components
        return bean;
    }/*w w w.ja v a  2  s .c  om*/
    ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            Annotation[] annotations = AnnotationUtils.getAnnotations(method);
            for (Annotation annotation : annotations) {
                MethodAnnotationPostProcessor postProcessor = postProcessors.get(annotation.annotationType());
                if (postProcessor != null && shouldCreateEndpoint(annotation)) {
                    Object result = postProcessor.postProcess(bean, beanName, method, annotation);
                    if (result != null && result instanceof AbstractEndpoint) {
                        String endpointBeanName = generateBeanName(beanName, method,
                                annotation.annotationType());
                        if (result instanceof BeanNameAware) {
                            ((BeanNameAware) result).setBeanName(endpointBeanName);
                        }
                        beanFactory.registerSingleton(endpointBeanName, result);
                        if (result instanceof BeanFactoryAware) {
                            ((BeanFactoryAware) result).setBeanFactory(beanFactory);
                        }
                        if (result instanceof InitializingBean) {
                            try {
                                ((InitializingBean) result).afterPropertiesSet();
                            } catch (Exception e) {
                                throw new BeanInitializationException(
                                        "failed to initialize annotated component", e);
                            }
                        }
                        if (result instanceof Lifecycle) {
                            lifecycles.add((Lifecycle) result);
                            if (result instanceof SmartLifecycle && ((SmartLifecycle) result).isAutoStartup()) {
                                ((SmartLifecycle) result).start();
                            }
                        }
                        if (result instanceof ApplicationListener) {
                            listeners.add((ApplicationListener) result);
                        }
                    }
                }
            }
        }
    });
    return bean;
}