Java Code Examples for org.springframework.util.ReflectionUtils#getAllDeclaredMethods()

The following examples show how to use org.springframework.util.ReflectionUtils#getAllDeclaredMethods() . 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: ConstructorResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve all candidate methods for the given class, considering
 * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag.
 * Called as the starting point for factory method determination.
 */
private Method[] getCandidateMethods(final Class<?> factoryClass, final RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
			@Override
			public Method[] run() {
				return (mbd.isNonPublicAccessAllowed() ?
						ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
			}
		});
	}
	else {
		return (mbd.isNonPublicAccessAllowed() ?
				ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
	}
}
 
Example 2
Source File: DeployerContextUtils.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
private static Method[] getCandidateMethods(final Class<?> factoryClass,
		final RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
			@Override
			public Method[] run() {
				return (mbd.isNonPublicAccessAllowed()
						? ReflectionUtils.getAllDeclaredMethods(factoryClass)
						: factoryClass.getMethods());
			}
		});
	}
	else {
		return (mbd.isNonPublicAccessAllowed()
				? ReflectionUtils.getAllDeclaredMethods(factoryClass)
				: factoryClass.getMethods());
	}
}
 
Example 3
Source File: ConstructorResolver.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve all candidate methods for the given class, considering
 * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag.
 * Called as the starting point for factory method determination.
 */
private Method[] getCandidateMethods(final Class<?> factoryClass, final RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
			@Override
			public Method[] run() {
				return (mbd.isNonPublicAccessAllowed() ?
						ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
			}
		});
	}
	else {
		return (mbd.isNonPublicAccessAllowed() ?
				ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
	}
}
 
Example 4
Source File: MythFeignBeanPostProcessor.java    From myth with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    if (!Proxy.isProxyClass(bean.getClass())) {
        return bean;
    }
    InvocationHandler handler = Proxy.getInvocationHandler(bean);

    final Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());

    for (Method method : methods) {
        Myth myth = AnnotationUtils.findAnnotation(method, Myth.class);
        if (Objects.nonNull(myth)) {
            MythFeignHandler mythFeignHandler = new MythFeignHandler();
            mythFeignHandler.setDelegate(handler);
            Class<?> clazz = bean.getClass();
            Class<?>[] interfaces = clazz.getInterfaces();
            ClassLoader loader = clazz.getClassLoader();
            return Proxy.newProxyInstance(loader, interfaces, mythFeignHandler);
        }
    }
    return bean;
}
 
Example 5
Source File: HmilyFeignBeanPostProcessor.java    From hmily with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    if (!Proxy.isProxyClass(bean.getClass())) {
        return bean;
    }
    InvocationHandler handler = Proxy.getInvocationHandler(bean);

    final Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());

    for (Method method : methods) {
        Hmily hmily = AnnotationUtils.findAnnotation(method, Hmily.class);
        if (Objects.nonNull(hmily)) {
            HmilyFeignHandler hmilyFeignHandler = new HmilyFeignHandler();
            hmilyFeignHandler.setDelegate(handler);
            Class<?> clazz = bean.getClass();
            Class<?>[] interfaces = clazz.getInterfaces();
            ClassLoader loader = clazz.getClassLoader();
            return Proxy.newProxyInstance(loader, interfaces, hmilyFeignHandler);
        }
    }
    return bean;
}
 
Example 6
Source File: PropertyDataProcessor.java    From choerodon-starters with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {

    Saga typeSaga = AnnotationUtils.findAnnotation(bean.getClass(), Saga.class);
    if (typeSaga != null) {
        PropertySaga data = new PropertySaga(typeSaga.code(), typeSaga.description());
        addInputSchema(typeSaga, data);
        propertyData.addSaga(data);
    }
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
    if (methods != null) {
        for (Method method : methods) {
            addMethodSaga(method);
            addMethodSagaTask(method);
            addMethodJobTask(bean, method);
        }
    }
    return bean;
}
 
Example 7
Source File: FunctionContextUtils.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
private static Method[] getCandidateMethods(final Class<?> factoryClass,
		final RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
			@Override
			public Method[] run() {
				return (mbd.isNonPublicAccessAllowed()
						? ReflectionUtils.getAllDeclaredMethods(factoryClass)
						: factoryClass.getMethods());
			}
		});
	}
	else {
		return (mbd.isNonPublicAccessAllowed()
				? ReflectionUtils.getAllDeclaredMethods(factoryClass)
				: factoryClass.getMethods());
	}
}
 
Example 8
Source File: BridgeMethodResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find the original method for the supplied {@link Method bridge Method}.
 * <p>It is safe to call this method passing in a non-bridge {@link Method} instance.
 * In such a case, the supplied {@link Method} instance is returned directly to the caller.
 * Callers are <strong>not</strong> required to check for bridging before calling this method.
 * @param bridgeMethod the method to introspect
 * @return the original method (either the bridged method or the passed-in method
 * if no more specific one could be found)
 */
public static Method findBridgedMethod(Method bridgeMethod) {
	if (bridgeMethod == null || !bridgeMethod.isBridge()) {
		return bridgeMethod;
	}
	// Gather all methods with matching name and parameter size.
	List<Method> candidateMethods = new ArrayList<Method>();
	Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass());
	for (Method candidateMethod : methods) {
		if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) {
			candidateMethods.add(candidateMethod);
		}
	}
	// Now perform simple quick check.
	if (candidateMethods.size() == 1) {
		return candidateMethods.get(0);
	}
	// Search for candidate match.
	Method bridgedMethod = searchCandidates(candidateMethods, bridgeMethod);
	if (bridgedMethod != null) {
		// Bridged method found...
		return bridgedMethod;
	}
	else {
		// A bridge method was passed in but we couldn't find the bridged method.
		// Let's proceed with the passed-in method and hope for the best...
		return bridgeMethod;
	}
}
 
Example 9
Source File: MessageListenerBeanPostProcessor.java    From koper with Apache License 2.0 5 votes vote down vote up
/**
 * 获取第一个方法
 *
 * @param clazz
 * @param methodName
 * @return
 */
protected Method getMethod(Class<?> clazz, String methodName) {

    Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); //clazz.getDeclaredMethods();
    Method findMethod = null;
    for (Method method : methods) {
        if (method.getName().equals(methodName)
                && method.getAnnotations().length != 0) {
            findMethod = method;
        }
    }
    return findMethod;
}
 
Example 10
Source File: SpringExpressionParser.java    From circus-train with Apache License 2.0 5 votes vote down vote up
SpringExpressionParser(Class<?>... functionHolders) {
  for (Class<?> functionHolder : functionHolders) {
    for (Method method : ReflectionUtils.getAllDeclaredMethods(functionHolder)) {
      if (isPublic(method.getModifiers()) && isStatic(method.getModifiers())) {
        evalContext.registerFunction(method.getName(), method);
      }
    }
  }
}
 
Example 11
Source File: ReflectionSupport.java    From bowman with Apache License 2.0 5 votes vote down vote up
private static Method getIdAccessor(Class<?> clazz) {
	for (Method method : ReflectionUtils.getAllDeclaredMethods(clazz)) {
		if (method.getAnnotation(ID_ACCESSOR_ANNOTATION) != null) {
			return method;
		}
	}
	
	throw new IllegalArgumentException(String.format("No @%s found for %s",
		ID_ACCESSOR_ANNOTATION.getSimpleName(), clazz.getName()));
}
 
Example 12
Source File: JaxbElementWrapper.java    From eclair with Apache License 2.0 5 votes vote down vote up
private Method findMethod(Class<?>[] classes, Class<?> parameterClass) {
    for (Class<?> clazz : classes) {
        if (nonNull(clazz.getAnnotation(XmlRegistry.class))) {
            for (Method method : ReflectionUtils.getAllDeclaredMethods(clazz)) {
                if (byParameterType(method, parameterClass) && byReturnType(method, parameterClass) && byAnnotation(method)) {
                    return method;
                }
            }
        }
    }
    return null;
}
 
Example 13
Source File: SagaTaskProcessor.java    From choerodon-starters with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
    if (methods != null) {
        for (Method method : methods) {
            SagaTask sagaTask = AnnotationUtils.getAnnotation(method, SagaTask.class);
            if (sagaTask != null) {
                String key = sagaTask.sagaCode() + sagaTask.code();
                errorCheck(method, sagaTask, key);
                invokeBeanMap.put(key, new SagaTaskInvokeBean(method, bean, sagaTask, key));
            }
        }
    }
    return bean;
}
 
Example 14
Source File: BridgeMethodResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Find the original method for the supplied {@link Method bridge Method}.
 * <p>It is safe to call this method passing in a non-bridge {@link Method} instance.
 * In such a case, the supplied {@link Method} instance is returned directly to the caller.
 * Callers are <strong>not</strong> required to check for bridging before calling this method.
 * @param bridgeMethod the method to introspect
 * @return the original method (either the bridged method or the passed-in method
 * if no more specific one could be found)
 */
public static Method findBridgedMethod(Method bridgeMethod) {
	if (bridgeMethod == null || !bridgeMethod.isBridge()) {
		return bridgeMethod;
	}
	// Gather all methods with matching name and parameter size.
	List<Method> candidateMethods = new ArrayList<Method>();
	Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass());
	for (Method candidateMethod : methods) {
		if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) {
			candidateMethods.add(candidateMethod);
		}
	}
	// Now perform simple quick check.
	if (candidateMethods.size() == 1) {
		return candidateMethods.get(0);
	}
	// Search for candidate match.
	Method bridgedMethod = searchCandidates(candidateMethods, bridgeMethod);
	if (bridgedMethod != null) {
		// Bridged method found...
		return bridgedMethod;
	}
	else {
		// A bridge method was passed in but we couldn't find the bridged method.
		// Let's proceed with the passed-in method and hope for the best...
		return bridgeMethod;
	}
}
 
Example 15
Source File: ConstructorResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Retrieve all candidate methods for the given class, considering
 * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag.
 * Called as the starting point for factory method determination.
 */
private Method[] getCandidateMethods(Class<?> factoryClass, RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged((PrivilegedAction<Method[]>) () ->
				(mbd.isNonPublicAccessAllowed() ?
					ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()));
	}
	else {
		return (mbd.isNonPublicAccessAllowed() ?
				ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
	}
}
 
Example 16
Source File: MethodInvokerConfig.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Finds the method on the target class that matches the target name and
 * returns the declared parameter types
 *
 * @return method parameter types
 */
protected Class[] getMethodArgumentTypes() {
    if (StringUtils.isNotBlank(staticMethod)) {
        int lastDotIndex = this.staticMethod.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == this.staticMethod.length()) {
            throw new IllegalArgumentException("staticMethod must be a fully qualified class plus method name: " +
                    "e.g. 'example.MyExampleClass.myExampleMethod'");
        }
        String className = this.staticMethod.substring(0, lastDotIndex);
        String methodName = this.staticMethod.substring(lastDotIndex + 1);
        try {
            setTargetClass(resolveClassName(className));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Unable to get class for name: " + className);
        }
        setTargetMethod(methodName);
    }

    Method matchingCandidate = findMatchingMethod();
    if (matchingCandidate != null) {
        return matchingCandidate.getParameterTypes();
    }

    Method[] candidates = ReflectionUtils.getAllDeclaredMethods(getTargetClass());
    for (Method candidate : candidates) {
        if (candidate.getName().equals(getTargetMethod())) {
            return candidate.getParameterTypes();
        }
    }

    return null;
}
 
Example 17
Source File: ConstructorResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Retrieve all candidate methods for the given class, considering
 * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag.
 * Called as the starting point for factory method determination.
 */
private Method[] getCandidateMethods(Class<?> factoryClass, RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		return AccessController.doPrivileged((PrivilegedAction<Method[]>) () ->
				(mbd.isNonPublicAccessAllowed() ?
					ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods()));
	}
	else {
		return (mbd.isNonPublicAccessAllowed() ?
				ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
	}
}
 
Example 18
Source File: MQAutoConfiguration.java    From elephant with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void onApplicationEvent(ContextRefreshedEvent event) {
	if(isRepeat){
		return;
	}
	this.isRepeat = true;
	this.applicationContext = event.getApplicationContext();
	for(String beanName : this.applicationContext.getBeanDefinitionNames()){
		Class<?> clz = this.applicationContext.getType(beanName);
		if(clz == null) continue;
		Method[] methods = ReflectionUtils.getAllDeclaredMethods(clz);
		if(methods == null || methods.length <= 0){
			continue;
		}
		for(Method method : methods){
			QueueListener queueListener = AnnotationUtils.findAnnotation(method, QueueListener.class);
			String registerBeanName = null;
			String retryRegisterBeanName = null;
			if(queueListener != null){
				registerBeanName = "queueConsumer" + count.getAndIncrement();
				this.registerListener(
						registerBeanName, 
						new ActiveMQQueue(queueListener.name()),
						this.applicationContext.getBean(beanName),
						method,
						queueListener.retryTimes(),
						false);
				retryRegisterBeanName = "retryQueueConsumer" + count.getAndIncrement();
				this.registerListener(
						retryRegisterBeanName, 
						new ActiveMQQueue(queueListener.name() + MQConstant.RETRY_QUEUE_SUFFIX),
						this.applicationContext.getBean(beanName),
						method,
						0,
						true);
			}
			TopicListnener topicListnener = AnnotationUtils.findAnnotation(method, TopicListnener.class);
			if(topicListnener != null){
				registerBeanName = "topicConsumer" + count.getAndIncrement();
				this.registerListener(
						registerBeanName, 
						new ActiveMQTopic(topicListnener.name()), 
						this.applicationContext.getBean(beanName),
						method,
						topicListnener.retryTimes(),
						false);
				retryRegisterBeanName = "retryTopicConsumer" + count.getAndIncrement();
				this.registerListener(
						retryRegisterBeanName, 
						new ActiveMQTopic(topicListnener.name() + MQConstant.RETRY_QUEUE_SUFFIX),
						this.applicationContext.getBean(beanName),
						method,
						0,
						true);
			}
			start(registerBeanName);
			start(retryRegisterBeanName);
		}
	}
}
 
Example 19
Source File: ArgumentConvertingMethodInvoker.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Actually find a method with matching parameter type, i.e. where each
 * argument value is assignable to the corresponding parameter type.
 * @param arguments the argument values to match against method parameters
 * @return a matching method, or {@code null} if none
 */
@Nullable
protected Method doFindMatchingMethod(Object[] arguments) {
	TypeConverter converter = getTypeConverter();
	if (converter != null) {
		String targetMethod = getTargetMethod();
		Method matchingMethod = null;
		int argCount = arguments.length;
		Class<?> targetClass = getTargetClass();
		Assert.state(targetClass != null, "No target class set");
		Method[] candidates = ReflectionUtils.getAllDeclaredMethods(targetClass);
		int minTypeDiffWeight = Integer.MAX_VALUE;
		Object[] argumentsToUse = null;
		for (Method candidate : candidates) {
			if (candidate.getName().equals(targetMethod)) {
				// Check if the inspected method has the correct number of parameters.
				Class<?>[] paramTypes = candidate.getParameterTypes();
				if (paramTypes.length == argCount) {
					Object[] convertedArguments = new Object[argCount];
					boolean match = true;
					for (int j = 0; j < argCount && match; j++) {
						// Verify that the supplied argument is assignable to the method parameter.
						try {
							convertedArguments[j] = converter.convertIfNecessary(arguments[j], paramTypes[j]);
						}
						catch (TypeMismatchException ex) {
							// Ignore -> simply doesn't match.
							match = false;
						}
					}
					if (match) {
						int typeDiffWeight = getTypeDifferenceWeight(paramTypes, convertedArguments);
						if (typeDiffWeight < minTypeDiffWeight) {
							minTypeDiffWeight = typeDiffWeight;
							matchingMethod = candidate;
							argumentsToUse = convertedArguments;
						}
					}
				}
			}
		}
		if (matchingMethod != null) {
			setArguments(argumentsToUse);
			return matchingMethod;
		}
	}
	return null;
}
 
Example 20
Source File: AopContextHolder.java    From Milkomeda with MIT License 4 votes vote down vote up
/**
 * 获取处理组件元数据
 * @param handlerAnnotationClazz    处理器注解类
 * @param executeAnnotationClazz    执行方法注解类
 * @param nameProvider              标识名称提供函数
 * @param onlyOneExecutorPerHandler 一个组件只有一个处理方法是传true
 * @return  Map
 */
public static Map<String, List<HandlerMetaData>> getHandlerMetaData(
        Class<? extends Annotation> handlerAnnotationClazz,
        Class<? extends Annotation> executeAnnotationClazz,
        BiFunction<Annotation, HandlerMetaData, String> nameProvider,
        boolean onlyOneExecutorPerHandler) {
    Map<String, List<HandlerMetaData>> handlerMap = new HashMap<>();
    Map<String, Object> beanMap = ApplicationContextHolder.get().getBeansWithAnnotation(handlerAnnotationClazz);
    for (String key : beanMap.keySet()) {
        Object target = beanMap.get(key);
        // 查找AOP切面(通过Proxy.isProxyClass()判断类是否是代理的接口类,AopUtils.isAopProxy()判断对象是否被代理),可以通过AopUtils.getTargetClass()获取原Class
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(AopUtils.isAopProxy(target) ?
                AopUtils.getTargetClass(target) : target.getClass());
        for (Method method : methods) {
            // 获取指定方法上的注解的属性
            final Annotation executeAnnotation = AnnotationUtils.findAnnotation(method, executeAnnotationClazz);
            if (null == executeAnnotation) {
                continue;
            }
            HandlerMetaData metaData = new HandlerMetaData();
            // 支持SpEL
            String name = nameProvider.apply(executeAnnotation, metaData);
            if (name.startsWith("'") || name.startsWith("@") || name.startsWith("#") || name.startsWith("T(") || name.startsWith("args[")) {
                name = ELContext.getValue(target, new Object[]{}, target.getClass(), method, name, String.class);
            }
            if (name == null) {
                throw new IllegalArgumentException("Please specify the [tag] of "+ executeAnnotation +" !");
            }
            metaData.setName(name);
            metaData.setTarget(target);
            metaData.setMethod(method);
            if (handlerMap.containsKey(name)) {
                handlerMap.get(name).add(metaData);
            } else {
                List<HandlerMetaData> list = new ArrayList<>();
                list.add(metaData);
                handlerMap.put(name, list);
            }
            // 如果一个组件只会有一个处理方法,直接返回
            if (onlyOneExecutorPerHandler) {
                break;
            }
        }
    }
    return handlerMap;
}