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.springframework.statemachine.processor.StateMachineMethodInvokerHelper.java

private Map<String, Map<Class<?>, HandlerMethod>> findHandlerMethodsForTarget(final Object targetObject,
        final Class<? extends Annotation> annotationType, final String methodName,
        final boolean requiresReply) {

    Map<String, Map<Class<?>, HandlerMethod>> handlerMethods = new HashMap<String, Map<Class<?>, HandlerMethod>>();

    final Map<Class<?>, HandlerMethod> candidateMethods = new HashMap<Class<?>, HandlerMethod>();
    final Map<Class<?>, HandlerMethod> candidateMessageMethods = new HashMap<Class<?>, HandlerMethod>();
    final Class<?> targetClass = this.getTargetClass(targetObject);
    MethodFilter methodFilter = new UniqueMethodFilter(targetClass);
    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        @Override//  w  w  w  . j a va2s. c o  m
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            boolean matchesAnnotation = false;
            if (method.isBridge()) {
                return;
            }
            if (isMethodDefinedOnObjectClass(method)) {
                return;
            }
            if (method.getDeclaringClass().equals(Proxy.class)) {
                return;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (requiresReply && void.class.equals(method.getReturnType())) {
                return;
            }
            if (methodName != null && !methodName.equals(method.getName())) {
                return;
            }
            if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) {
                matchesAnnotation = true;
            }
            HandlerMethod handlerMethod = null;
            try {
                handlerMethod = new HandlerMethod(method);
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Method [" + method + "] is not eligible for container handling.", e);
                }
                return;
            }
            Class<?> targetParameterType = handlerMethod.getTargetParameterType();
            if (matchesAnnotation || annotationType == null) {
                if (handlerMethod.isMessageMethod()) {
                    if (candidateMessageMethods.containsKey(targetParameterType)) {
                        throw new IllegalArgumentException("Found more than one method match for type "
                                + "[Message<" + targetParameterType + ">]");
                    }
                    candidateMessageMethods.put(targetParameterType, handlerMethod);
                } else {
                    if (candidateMethods.containsKey(targetParameterType)) {
                        String exceptionMessage = "Found more than one method match for ";
                        if (Void.class.equals(targetParameterType)) {
                            exceptionMessage += "empty parameter for 'payload'";
                        } else {
                            exceptionMessage += "type [" + targetParameterType + "]";
                        }
                        throw new IllegalArgumentException(exceptionMessage);
                    }
                    candidateMethods.put(targetParameterType, handlerMethod);
                }
            }
        }
    }, methodFilter);

    if (!candidateMethods.isEmpty() || !candidateMessageMethods.isEmpty()) {
        handlerMethods.put(CANDIDATE_METHODS, candidateMethods);
        handlerMethods.put(CANDIDATE_MESSAGE_METHODS, candidateMessageMethods);
        return handlerMethods;
    }

    Assert.state(!handlerMethods.isEmpty(), "Target object of type [" + this.targetObject.getClass()
            + "] has no eligible methods for handling Container.");

    return handlerMethods;
}

From source file:org.springframework.xd.dirt.stream.FileSourceModuleTests.java

@Test
public void testSplitterUsesIterator() throws Exception {
    System.out.println(System.getProperty("user.dir"));
    ConfigurableApplicationContext ctx = new FileSystemXmlApplicationContext(
            new String[] { "../modules/common/file-source-common-context.xml",
                    "classpath:org/springframework/xd/dirt/stream/ppc-context.xml" },
            false);//w ww .j  a  va 2s . c o m
    StandardEnvironment env = new StandardEnvironment();
    Properties props = new Properties();
    props.setProperty("fixedDelay", "5");
    props.setProperty("timeUnit", "SECONDS");
    props.setProperty("initialDelay", "0");
    props.setProperty("withMarkers", "false");
    PropertiesPropertySource pps = new PropertiesPropertySource("props", props);
    env.getPropertySources().addLast(pps);
    env.setActiveProfiles("use-contents-with-split");
    ctx.setEnvironment(env);
    ctx.refresh();
    FileSplitter splitter = ctx.getBean(FileSplitter.class);
    File foo = File.createTempFile("foo", ".txt");
    final AtomicReference<Method> splitMessage = new AtomicReference<>();
    ReflectionUtils.doWithMethods(FileSplitter.class, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            method.setAccessible(true);
            splitMessage.set(method);
        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return method.getName().equals("splitMessage");
        }
    });
    Object result = splitMessage.get().invoke(splitter, new GenericMessage<File>(foo));
    assertThat(result, instanceOf(Iterator.class));
    ctx.close();
    foo.delete();
}

From source file:org.tinygroup.springmvc.coc.impl.AbstractConventionHandlerMethodResolver.java

public Set<String> resolve() {
    final Set<String> urlList = new HashSet<String>();// for this handler
    String className = handlerType.getName();
    // /*from w  w w. j a va2 s. c om*/
    final StringBuilder uri = new StringBuilder("/");
    int lastpos = className.indexOf("." + conventionHelper.getHandlerStyle());
    int startpos = className.indexOf("web.");
    startpos += 5;
    String path = StringUtils.EMPTY;
    if (startpos < lastpos) {
        path = StringUtils.substring(className, startpos, lastpos);
        path = path.replace(".", "/");
        uri.append(path).append("/");
    }
    // uri-prefix. => /namespace/
    String resourcesName = conventionHelper.getHandlerName(getHandlerType());
    uri.append(resourcesName);

    ReflectionUtils.doWithMethods(getHandlerType(), new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) {
            if (!qualify(method)) {
                return;
            }
            // method should be public.
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (method.isAnnotationPresent(RequestMapping.class)) {
                return;
            } else if (method.isAnnotationPresent(InitBinder.class)) {
                return;
            } else if (method.isAnnotationPresent(ModelAttribute.class)) {
                return;
            } else {
                List<String> urls = doResolve(uri.toString(), method);
                if (!CollectionUtil.isEmpty(urls)) {
                    for (String url : urls) {
                        urlList.add(url);
                    }
                }
            }
        }
    }, new MethodFilter() {
        // ==object.class
        public boolean matches(Method method) {
            return method.getDeclaringClass() != Object.class;
        }

    });
    return urlList;
}

From source file:org.treediagram.nina.console.Console.java

/**
 * ?// w  w  w. j  a  v  a 2s  . co m
 */
private void registerCommand() {
    Map<String, Object> beans = applicationContext.getBeansWithAnnotation(ConsoleBean.class);

    for (Entry<String, Object> entry : beans.entrySet()) {
        final Object bean = entry.getValue();
        final Class<? extends Object> beanClass = bean.getClass();

        final ConsoleBean consoleBean = beanClass.getAnnotation(ConsoleBean.class);
        final String groupName = consoleBean.value();

        ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                // 
                Command command = new MethodCommand(bean, method, conversionService);

                // 
                if (StringUtils.isNotBlank(groupName)) {
                    // ?
                    Map<String, Command> group = groupedCommands.get(groupName);
                    if (group == null) {
                        group = new HashMap<String, Command>();
                        groupedCommands.put(groupName, group);
                    }

                    // 
                    if (group.containsKey(command.name())) {
                        throw new IllegalStateException(
                                "[" + groupName + "][" + command.name() + "]??");
                    }
                    group.put(command.name(), command);
                } else {
                    // ???
                    if (groupedCommands.containsKey(command.name())) {
                        throw new IllegalStateException("[" + command.name() + "]???");
                    }
                    // 
                    if (commands.containsKey(command.name())) {
                        throw new IllegalStateException("[" + command.name() + "]??");
                    }
                    commands.put(command.name(), command);
                }
            }
        }, findCommand);
    }
}