Java Code Examples for org.springframework.core.MethodIntrospector#selectMethods()

The following examples show how to use org.springframework.core.MethodIntrospector#selectMethods() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MvcUriComponentsBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
private static Method getMethod(Class<?> controllerType, final String methodName, final Object... args) {
	MethodFilter selector = method -> {
		String name = method.getName();
		int argLength = method.getParameterCount();
		return (name.equals(methodName) && argLength == args.length);
	};
	Set<Method> methods = MethodIntrospector.selectMethods(controllerType, selector);
	if (methods.size() == 1) {
		return methods.iterator().next();
	}
	else if (methods.size() > 1) {
		throw new IllegalArgumentException(String.format(
				"Found two methods named '%s' accepting arguments %s in controller %s: [%s]",
				methodName, Arrays.asList(args), controllerType.getName(), methods));
	}
	else {
		throw new IllegalArgumentException("No method named '" + methodName + "' with " + args.length +
				" arguments found in controller " + controllerType.getName());
	}
}
 
Example 2
Source File: AbstractHandlerMethodMapping.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Look for handler methods in a handler.
 * @param handler the bean name of a handler or a handler instance
 */
protected void detectHandlerMethods(final Object handler) {
	Class<?> handlerType = (handler instanceof String ?
			obtainApplicationContext().getType((String) handler) : handler.getClass());

	if (handlerType != null) {
		final Class<?> userType = ClassUtils.getUserClass(handlerType);
		Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
				(MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));
		if (logger.isTraceEnabled()) {
			logger.trace(formatMappings(userType, methods));
		}
		methods.forEach((key, mapping) -> {
			Method invocableMethod = AopUtils.selectInvocableMethod(key, userType);
			registerHandlerMethod(handler, invocableMethod, mapping);
		});
	}
}
 
Example 3
Source File: MvcUriComponentsBuilder.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private static Method getMethod(Class<?> controllerType, final String methodName, final Object... args) {
	MethodFilter selector = new MethodFilter() {
		@Override
		public boolean matches(Method method) {
			String name = method.getName();
			int argLength = method.getParameterTypes().length;
			return (name.equals(methodName) && argLength == args.length);
		}
	};
	Set<Method> methods = MethodIntrospector.selectMethods(controllerType, selector);
	if (methods.size() == 1) {
		return methods.iterator().next();
	}
	else if (methods.size() > 1) {
		throw new IllegalArgumentException(String.format(
				"Found two methods named '%s' accepting arguments %s in controller %s: [%s]",
				methodName, Arrays.asList(args), controllerType.getName(), methods));
	}
	else {
		throw new IllegalArgumentException("No method named '" + methodName + "' with " + args.length +
				" arguments found in controller " + controllerType.getName());
	}
}
 
Example 4
Source File: AbstractHandlerMethodMapping.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Look for handler methods in a handler.
 * @param handler the bean name of a handler or a handler instance
 */
protected void detectHandlerMethods(final Object handler) {
	Class<?> handlerType = (handler instanceof String ?
			obtainApplicationContext().getType((String) handler) : handler.getClass());

	if (handlerType != null) {
		final Class<?> userType = ClassUtils.getUserClass(handlerType);
		Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
				(MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));
		if (logger.isTraceEnabled()) {
			logger.trace(formatMappings(userType, methods));
		}
		methods.forEach((method, mapping) -> {
			Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
			registerHandlerMethod(handler, invocableMethod, mapping);
		});
	}
}
 
Example 5
Source File: RedisListenerProcessor.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, final String beanName) {
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    Map<Method, RedisListener> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
            (MethodIntrospector.MetadataLookup<RedisListener>) method -> AnnotatedElementUtils.findMergedAnnotation(method, RedisListener.class));
    annotatedMethods.forEach((method, v) -> {
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(bean, method.getName());
        messageListenerAdapter.afterPropertiesSet();
        String[] channels = v.value();
        for (String channel : channels) {
            redisMessageListenerContainer.addMessageListener(messageListenerAdapter, channel.contains("*") ? new PatternTopic(channel) : new ChannelTopic(channel));
        }
    });
    return bean;
}
 
Example 6
Source File: AbstractHandlerMethodMapping.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Look for handler methods in a handler.
 * @param handler the bean name of a handler or a handler instance
 */
protected void detectHandlerMethods(final Object handler) {
	Class<?> handlerType = (handler instanceof String ?
			getApplicationContext().getType((String) handler) : handler.getClass());
	final Class<?> userType = ClassUtils.getUserClass(handlerType);

	Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
			new MethodIntrospector.MetadataLookup<T>() {
				@Override
				public T inspect(Method method) {
					try {
						return getMappingForMethod(method, userType);
					}
					catch (Throwable ex) {
						throw new IllegalStateException("Invalid mapping on handler class [" +
								userType.getName() + "]: " + method, ex);
					}
				}
			});

	if (logger.isDebugEnabled()) {
		logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
	}
	for (Map.Entry<Method, T> entry : methods.entrySet()) {
		Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);
		T mapping = entry.getValue();
		registerHandlerMethod(handler, invocableMethod, mapping);
	}
}
 
Example 7
Source File: MethodMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static Map<Class<? extends Throwable>, Method> initExceptionMappings(Class<?> handlerType) {
	Map<Class<? extends Throwable>, Method> result = new HashMap<>();
	for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHOD_FILTER)) {
		for (Class<? extends Throwable> exception : getExceptionsFromMethodSignature(method)) {
			result.put(exception, method);
		}
	}
	return result;
}
 
Example 8
Source File: ModelFactoryOrderingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void runTest(Object controller) throws Exception {
	HandlerMethodArgumentResolverComposite resolvers = new HandlerMethodArgumentResolverComposite();
	resolvers.addResolver(new ModelAttributeMethodProcessor(false));
	resolvers.addResolver(new ModelMethodProcessor());
	WebDataBinderFactory dataBinderFactory = new DefaultDataBinderFactory(null);

	Class<?> type = controller.getClass();
	Set<Method> methods = MethodIntrospector.selectMethods(type, METHOD_FILTER);
	List<InvocableHandlerMethod> modelMethods = new ArrayList<>();
	for (Method method : methods) {
		InvocableHandlerMethod modelMethod = new InvocableHandlerMethod(controller, method);
		modelMethod.setHandlerMethodArgumentResolvers(resolvers);
		modelMethod.setDataBinderFactory(dataBinderFactory);
		modelMethods.add(modelMethod);
	}
	Collections.shuffle(modelMethods);

	SessionAttributesHandler sessionHandler = new SessionAttributesHandler(type, this.sessionAttributeStore);
	ModelFactory factory = new ModelFactory(modelMethods, dataBinderFactory, sessionHandler);
	factory.initModel(this.webRequest, this.mavContainer, new HandlerMethod(controller, "handle"));
	if (logger.isDebugEnabled()) {
		StringBuilder sb = new StringBuilder();
		for (String name : getInvokedMethods()) {
			sb.append(" >> ").append(name);
		}
		logger.debug(sb);
	}
}
 
Example 9
Source File: ExceptionHandlerMethodResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A constructor that finds {@link ExceptionHandler} methods in the given type.
 * @param handlerType the type to introspect
 */
public ExceptionHandlerMethodResolver(Class<?> handlerType) {
	for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHODS)) {
		for (Class<? extends Throwable> exceptionType : detectExceptionMappings(method)) {
			addExceptionMapping(exceptionType, method);
		}
	}
}
 
Example 10
Source File: ExceptionHandlerMethodResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * A constructor that finds {@link ExceptionHandler} methods in the given type.
 * @param handlerType the type to introspect
 */
public ExceptionHandlerMethodResolver(Class<?> handlerType) {
	for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHODS)) {
		for (Class<? extends Throwable> exceptionType : detectExceptionMappings(method)) {
			addExceptionMapping(exceptionType, method);
		}
	}
}
 
Example 11
Source File: JmsListenerAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
	if (bean instanceof AopInfrastructureBean || bean instanceof JmsListenerContainerFactory ||
			bean instanceof JmsListenerEndpointRegistry) {
		// Ignore AOP infrastructure such as scoped proxies.
		return bean;
	}

	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
	if (!this.nonAnnotatedClasses.contains(targetClass)) {
		Map<Method, Set<JmsListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
				(MethodIntrospector.MetadataLookup<Set<JmsListener>>) method -> {
					Set<JmsListener> listenerMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
							method, JmsListener.class, JmsListeners.class);
					return (!listenerMethods.isEmpty() ? listenerMethods : null);
				});
		if (annotatedMethods.isEmpty()) {
			this.nonAnnotatedClasses.add(targetClass);
			if (logger.isTraceEnabled()) {
				logger.trace("No @JmsListener annotations found on bean type: " + targetClass);
			}
		}
		else {
			// Non-empty set of methods
			annotatedMethods.forEach((method, listeners) ->
					listeners.forEach(listener -> processJmsListener(listener, method, bean)));
			if (logger.isDebugEnabled()) {
				logger.debug(annotatedMethods.size() + " @JmsListener methods processed on bean '" + beanName +
						"': " + annotatedMethods);
			}
		}
	}
	return bean;
}
 
Example 12
Source File: ModelFactoryOrderingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void runTest(Object controller) throws Exception {
	HandlerMethodArgumentResolverComposite resolvers = new HandlerMethodArgumentResolverComposite();
	resolvers.addResolver(new ModelAttributeMethodProcessor(false));
	resolvers.addResolver(new ModelMethodProcessor());
	WebDataBinderFactory dataBinderFactory = new DefaultDataBinderFactory(null);

	Class<?> type = controller.getClass();
	Set<Method> methods = MethodIntrospector.selectMethods(type, METHOD_FILTER);
	List<InvocableHandlerMethod> modelMethods = new ArrayList<>();
	for (Method method : methods) {
		InvocableHandlerMethod modelMethod = new InvocableHandlerMethod(controller, method);
		modelMethod.setHandlerMethodArgumentResolvers(resolvers);
		modelMethod.setDataBinderFactory(dataBinderFactory);
		modelMethods.add(modelMethod);
	}
	Collections.shuffle(modelMethods);

	SessionAttributesHandler sessionHandler = new SessionAttributesHandler(type, this.sessionAttributeStore);
	ModelFactory factory = new ModelFactory(modelMethods, dataBinderFactory, sessionHandler);
	factory.initModel(this.webRequest, this.mavContainer, new HandlerMethod(controller, "handle"));
	if (logger.isDebugEnabled()) {
		StringBuilder sb = new StringBuilder();
		for (String name : getInvokedMethods()) {
			sb.append(" >> ").append(name);
		}
		logger.debug(sb);
	}
}
 
Example 13
Source File: SpringUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static Set<Method> selectMethodsByParameterTypes(Class<?> targetClass, String targetMethod, Method sourceMethod) {
	Set<Method> methods = MethodIntrospector.selectMethods(targetClass, (MethodFilter)method -> {
		return method.getName().equals(targetMethod) && 
				method.getParameterCount()==sourceMethod.getParameterCount() &&
				Objects.deepEquals(method.getParameterTypes(), sourceMethod.getParameterTypes());
	});
	return methods;
}
 
Example 14
Source File: RequestMappingHandlerAdapter.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private void initControllerAdviceCache() {
	if (getApplicationContext() == null) {
		return;
	}
	if (logger.isInfoEnabled()) {
		logger.info("Looking for @ControllerAdvice: " + getApplicationContext());
	}

	List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
	AnnotationAwareOrderComparator.sort(beans);

	List<Object> requestResponseBodyAdviceBeans = new ArrayList<Object>();

	for (ControllerAdviceBean bean : beans) {
		Set<Method> attrMethods = MethodIntrospector.selectMethods(bean.getBeanType(), MODEL_ATTRIBUTE_METHODS);
		if (!attrMethods.isEmpty()) {
			this.modelAttributeAdviceCache.put(bean, attrMethods);
			if (logger.isInfoEnabled()) {
				logger.info("Detected @ModelAttribute methods in " + bean);
			}
		}
		Set<Method> binderMethods = MethodIntrospector.selectMethods(bean.getBeanType(), INIT_BINDER_METHODS);
		if (!binderMethods.isEmpty()) {
			this.initBinderAdviceCache.put(bean, binderMethods);
			if (logger.isInfoEnabled()) {
				logger.info("Detected @InitBinder methods in " + bean);
			}
		}
		if (RequestBodyAdvice.class.isAssignableFrom(bean.getBeanType())) {
			requestResponseBodyAdviceBeans.add(bean);
			if (logger.isInfoEnabled()) {
				logger.info("Detected RequestBodyAdvice bean in " + bean);
			}
		}
		if (ResponseBodyAdvice.class.isAssignableFrom(bean.getBeanType())) {
			requestResponseBodyAdviceBeans.add(bean);
			if (logger.isInfoEnabled()) {
				logger.info("Detected ResponseBodyAdvice bean in " + bean);
			}
		}
	}

	if (!requestResponseBodyAdviceBeans.isEmpty()) {
		this.requestResponseBodyAdvice.addAll(0, requestResponseBodyAdviceBeans);
	}
}
 
Example 15
Source File: RequestMappingHandlerAdapter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void initControllerAdviceCache() {
	if (getApplicationContext() == null) {
		return;
	}
	if (logger.isInfoEnabled()) {
		logger.info("Looking for @ControllerAdvice: " + getApplicationContext());
	}

	List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
	AnnotationAwareOrderComparator.sort(beans);

	List<Object> requestResponseBodyAdviceBeans = new ArrayList<Object>();

	for (ControllerAdviceBean bean : beans) {
		Set<Method> attrMethods = MethodIntrospector.selectMethods(bean.getBeanType(), MODEL_ATTRIBUTE_METHODS);
		if (!attrMethods.isEmpty()) {
			this.modelAttributeAdviceCache.put(bean, attrMethods);
			if (logger.isInfoEnabled()) {
				logger.info("Detected @ModelAttribute methods in " + bean);
			}
		}
		Set<Method> binderMethods = MethodIntrospector.selectMethods(bean.getBeanType(), INIT_BINDER_METHODS);
		if (!binderMethods.isEmpty()) {
			this.initBinderAdviceCache.put(bean, binderMethods);
			if (logger.isInfoEnabled()) {
				logger.info("Detected @InitBinder methods in " + bean);
			}
		}
		if (RequestBodyAdvice.class.isAssignableFrom(bean.getBeanType())) {
			requestResponseBodyAdviceBeans.add(bean);
			if (logger.isInfoEnabled()) {
				logger.info("Detected RequestBodyAdvice bean in " + bean);
			}
		}
		if (ResponseBodyAdvice.class.isAssignableFrom(bean.getBeanType())) {
			requestResponseBodyAdviceBeans.add(bean);
			if (logger.isInfoEnabled()) {
				logger.info("Detected ResponseBodyAdvice bean in " + bean);
			}
		}
	}

	if (!requestResponseBodyAdviceBeans.isEmpty()) {
		this.requestResponseBodyAdvice.addAll(0, requestResponseBodyAdviceBeans);
	}
}
 
Example 16
Source File: ResolvableMethod.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Build a {@code ResolvableMethod} from the provided filters which must
 * resolve to a unique, single method.
 * <p>See additional resolveXxx shortcut methods going directly to
 * {@link Method} or return type parameter.
 * @throws IllegalStateException for no match or multiple matches
 */
public ResolvableMethod build() {
	Set<Method> methods = MethodIntrospector.selectMethods(this.objectClass, this::isMatch);
	Assert.state(!methods.isEmpty(), () -> "No matching method: " + this);
	Assert.state(methods.size() == 1, () -> "Multiple matching methods: " + this + formatMethods(methods));
	return new ResolvableMethod(methods.iterator().next());
}
 
Example 17
Source File: ResolvableMethod.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Build a {@code ResolvableMethod} from the provided filters which must
 * resolve to a unique, single method.
 * <p>See additional resolveXxx shortcut methods going directly to
 * {@link Method} or return type parameter.
 * @throws IllegalStateException for no match or multiple matches
 */
public ResolvableMethod build() {
	Set<Method> methods = MethodIntrospector.selectMethods(this.objectClass, this::isMatch);
	Assert.state(!methods.isEmpty(), () -> "No matching method: " + this);
	Assert.state(methods.size() == 1, () -> "Multiple matching methods: " + this + formatMethods(methods));
	return new ResolvableMethod(methods.iterator().next());
}
 
Example 18
Source File: ResolvableMethod.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Build a {@code ResolvableMethod} from the provided filters which must
 * resolve to a unique, single method.
 * <p>See additional resolveXxx shortcut methods going directly to
 * {@link Method} or return type parameter.
 * @throws IllegalStateException for no match or multiple matches
 */
public ResolvableMethod build() {
	Set<Method> methods = MethodIntrospector.selectMethods(this.objectClass, this::isMatch);
	Assert.state(!methods.isEmpty(), () -> "No matching method: " + this);
	Assert.state(methods.size() == 1, () -> "Multiple matching methods: " + this + formatMethods(methods));
	return new ResolvableMethod(methods.iterator().next());
}
 
Example 19
Source File: HandlerMethodSelector.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Select handler methods for the given handler type.
 * <p>Callers define handler methods of interest through the {@link MethodFilter} parameter.
 * @param handlerType the handler type to search handler methods on
 * @param handlerMethodFilter a {@link MethodFilter} to help recognize handler methods of interest
 * @return the selected methods, or an empty set
 * @see MethodIntrospector#selectMethods(Class, MethodFilter)
 */
public static Set<Method> selectMethods(Class<?> handlerType, MethodFilter handlerMethodFilter) {
	return MethodIntrospector.selectMethods(handlerType, handlerMethodFilter);
}
 
Example 20
Source File: HandlerMethodSelector.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Select handler methods for the given handler type.
 * <p>Callers define handler methods of interest through the {@link MethodFilter} parameter.
 * @param handlerType the handler type to search handler methods on
 * @param handlerMethodFilter a {@link MethodFilter} to help recognize handler methods of interest
 * @return the selected methods, or an empty set
 * @see MethodIntrospector#selectMethods(Class, MethodFilter)
 */
public static Set<Method> selectMethods(Class<?> handlerType, MethodFilter handlerMethodFilter) {
	return MethodIntrospector.selectMethods(handlerType, handlerMethodFilter);
}