Java Code Examples for org.springframework.util.ClassUtils#getUserClass()

The following examples show how to use org.springframework.util.ClassUtils#getUserClass() . 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: AbstractMethodMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Detect if the given handler has any methods that can handle messages and if
 * so register it with the extracted mapping information.
 * @param handler the handler to check, either an instance of a Spring bean name
 */
protected final void detectHandlerMethods(final Object handler) {
	Class<?> handlerType;
	if (handler instanceof String) {
		ApplicationContext context = getApplicationContext();
		Assert.state(context != null, "ApplicationContext is required for resolving handler bean names");
		handlerType = context.getType((String) handler);
	}
	else {
		handlerType = 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.isDebugEnabled()) {
			logger.debug(methods.size() + " message handler methods found on " + userType + ": " + methods);
		}
		methods.forEach((key, value) -> registerHandlerMethod(handler, key, value));
	}
}
 
Example 2
Source File: AbstractHandlerMethodMapping.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Look for handler methods in the specified handler bean.
 * @param handler either a bean name or an actual handler instance
 * @see #getMappingForMethod
 */
protected void detectHandlerMethods(Object handler) {
	Class<?> handlerType = (handler instanceof String ?
			obtainApplicationContext().getType((String) handler) : handler.getClass());

	if (handlerType != null) {
		Class<?> userType = ClassUtils.getUserClass(handlerType);
		Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
				(MethodIntrospector.MetadataLookup<T>) method -> {
					try {
						return getMappingForMethod(method, userType);
					}
					catch (Throwable ex) {
						throw new IllegalStateException("Invalid mapping on handler class [" +
								userType.getName() + "]: " + method, ex);
					}
				});
		if (logger.isTraceEnabled()) {
			logger.trace(formatMappings(userType, methods));
		}
		methods.forEach((method, mapping) -> {
			Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
			registerHandlerMethod(handler, invocableMethod, mapping);
		});
	}
}
 
Example 3
Source File: AbstractHandlerMethodMapping.java    From spring4-understanding with Apache License 2.0 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 ?
			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) {
					return getMappingForMethod(method, userType);
				}
			});

	if (logger.isDebugEnabled()) {
		logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
	}
	for (Map.Entry<Method, T> entry : methods.entrySet()) {
		registerHandlerMethod(handler, entry.getKey(), entry.getValue());
	}
}
 
Example 4
Source File: AopDataSourceSwitcherAutoConfiguration.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(Method method, Class<?> aClass) {
    Class<?> targetClass = ClassUtils.getUserClass(aClass);

    CacheKey key = new CacheKey(targetClass, method);
    matchers.stream()
            .filter(matcher -> matcher.match(targetClass, method))
            .findFirst()
            .ifPresent((matcher) -> cache.put(key, matcher));

    boolean datasourceMatched = cache.containsKey(key);
    boolean tableMatched = false;
    if (null != tableSwitcher) {
        CachedTableSwitchStrategyMatcher.CacheKey tableCacheKey = new CachedTableSwitchStrategyMatcher
                .CacheKey(targetClass, method);
        tableSwitcher.stream()
                .filter(matcher -> matcher.match(targetClass, method))
                .findFirst()
                .ifPresent((matcher) -> tableCache.put(tableCacheKey, matcher));
        tableMatched = tableCache.containsKey(tableCacheKey);
    }

    return datasourceMatched || tableMatched;
}
 
Example 5
Source File: DeprecatedBeanWarner.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (isLogEnabled()) {
		String[] beanNames = beanFactory.getBeanDefinitionNames();
		for (String beanName : beanNames) {
			String nameToLookup = beanName;
			if (beanFactory.isFactoryBean(beanName)) {
				nameToLookup = BeanFactory.FACTORY_BEAN_PREFIX + beanName;
			}
			Class<?> beanType = ClassUtils.getUserClass(beanFactory.getType(nameToLookup));
			if (beanType != null && beanType.isAnnotationPresent(Deprecated.class)) {
				BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
				logDeprecatedBean(beanName, beanType, beanDefinition);
			}
		}
	}
}
 
Example 6
Source File: EntityVo.java    From java-platform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object obj) {

	if (null == obj) {
		return false;
	}

	if (this == obj) {
		return true;
	}

	Class<?> thisClass = ClassUtils.getUserClass(getClass());
	Class<?> objClass = ClassUtils.getUserClass(obj.getClass());

	if (!(ClassUtils.isAssignable(thisClass, objClass) || ClassUtils.isAssignable(objClass, thisClass))) {
		return false;
	}

	EntityVo<?> that = (EntityVo<?>) obj;

	return null == this.getId() ? false : this.getId().equals(that.getId());
}
 
Example 7
Source File: HandlerMethod.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create an instance from a bean name, a method, and a {@code BeanFactory}.
 * The method {@link #createWithResolvedBean()} may be used later to
 * re-create the {@code HandlerMethod} with an initialized bean.
 */
public HandlerMethod(String beanName, BeanFactory beanFactory, Method method) {
	Assert.hasText(beanName, "Bean name is required");
	Assert.notNull(beanFactory, "BeanFactory is required");
	Assert.notNull(method, "Method is required");
	this.bean = beanName;
	this.beanFactory = beanFactory;
	Class<?> beanType = beanFactory.getType(beanName);
	if (beanType == null) {
		throw new IllegalStateException("Cannot resolve bean type for bean with name '" + beanName + "'");
	}
	this.beanType = ClassUtils.getUserClass(beanType);
	this.method = method;
	this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
	this.parameters = initMethodParameters();
}
 
Example 8
Source File: HandlerMethod.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create an instance from a bean name, a method, and a {@code BeanFactory}.
 * The method {@link #createWithResolvedBean()} may be used later to
 * re-create the {@code HandlerMethod} with an initialized bean.
 */
public HandlerMethod(String beanName, BeanFactory beanFactory, Method method) {
	Assert.hasText(beanName, "Bean name is required");
	Assert.notNull(beanFactory, "BeanFactory is required");
	Assert.notNull(method, "Method is required");
	this.bean = beanName;
	this.beanFactory = beanFactory;
	Class<?> beanType = beanFactory.getType(beanName);
	if (beanType == null) {
		throw new IllegalStateException("Cannot resolve bean type for bean with name '" + beanName + "'");
	}
	this.beanType = ClassUtils.getUserClass(beanType);
	this.method = method;
	this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
	this.parameters = initMethodParameters();
}
 
Example 9
Source File: ConstructorResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected Constructor<?> getUserDeclaredConstructor(Constructor<?> constructor) {
	Class<?> declaringClass = constructor.getDeclaringClass();
	Class<?> userClass = ClassUtils.getUserClass(declaringClass);
	if (userClass != declaringClass) {
		try {
			return userClass.getDeclaredConstructor(constructor.getParameterTypes());
		}
		catch (NoSuchMethodException ex) {
			// No equivalent constructor on user class (superclass)...
			// Let's proceed with the given constructor as we usually would.
		}
	}
	return constructor;
}
 
Example 10
Source File: AbstractAutowireCapableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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
 */
@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);
			}
		}
	}, ReflectionUtils.USER_DECLARED_METHODS);

	return (objectType.value != null && Object.class != objectType.value ? objectType.value : null);
}
 
Example 11
Source File: DefaultArangoConverter.java    From spring-data with Apache License 2.0 5 votes vote down vote up
private void addTypeKeyIfNecessary(
	final TypeInformation<?> definedType,
	final Object value,
	final VPackBuilder sink) {

	final Class<?> referenceType = definedType != null ? definedType.getType() : Object.class;
	final Class<?> valueType = ClassUtils.getUserClass(value.getClass());
	if (!valueType.equals(referenceType)) {
		typeMapper.writeType(valueType, sink);
	}
}
 
Example 12
Source File: HandlerMethod.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create an instance from a bean instance, method name, and parameter types.
 * @throws NoSuchMethodException when the method cannot be found
 */
public HandlerMethod(Object bean, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {
	Assert.notNull(bean, "Bean is required");
	Assert.notNull(methodName, "Method name is required");
	this.bean = bean;
	this.beanFactory = null;
	this.beanType = ClassUtils.getUserClass(bean);
	this.method = bean.getClass().getMethod(methodName, parameterTypes);
	this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(this.method);
	this.parameters = initMethodParameters();
}
 
Example 13
Source File: FastBeanCopier.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static Copier getCopier(Object source, Object target, boolean autoCreate) {
    Class sourceType = source instanceof Map ? Map.class : ClassUtils.getUserClass(source);
    Class targetType = target instanceof Map ? Map.class : ClassUtils.getUserClass(target);
    CacheKey key = createCacheKey(sourceType, targetType);
    if (autoCreate) {
        return CACHE.computeIfAbsent(key, k -> createCopier(sourceType, targetType));
    } else {
        return CACHE.get(key);
    }

}
 
Example 14
Source File: AnnotationMethodHandlerAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build a HandlerMethodResolver for the given handler type.
 */
private ServletHandlerMethodResolver getMethodResolver(Object handler) {
	Class<?> handlerClass = ClassUtils.getUserClass(handler);
	ServletHandlerMethodResolver resolver = this.methodResolverCache.get(handlerClass);
	if (resolver == null) {
		synchronized (this.methodResolverCache) {
			resolver = this.methodResolverCache.get(handlerClass);
			if (resolver == null) {
				resolver = new ServletHandlerMethodResolver(handlerClass);
				this.methodResolverCache.put(handlerClass, resolver);
			}
		}
	}
	return resolver;
}
 
Example 15
Source File: HibernateDao.java    From opencron with Apache License 2.0 5 votes vote down vote up
/**
 * 获取实体对象的真实类型,避免Spring代理对象
 *
 * @param entity
 * @return
 */
private static Class getEntityClass(Object entity) {
    if (entity instanceof Class) {
        return ClassUtils.getUserClass((Class) entity);
    }
    return ClassUtils.getUserClass(entity);
}
 
Example 16
Source File: AbstractFallbackTransactionAttributeSource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Same signature as {@link #getTransactionAttribute}, but doesn't cache the result.
 * {@link #getTransactionAttribute} is effectively a caching decorator for this method.
 * <p>As of 4.1.8, this method can be overridden.
 * @since 4.1.8
 * @see #getTransactionAttribute
 */
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {
	// Don't allow no-public methods as required.
	if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
		return null;
	}

	// Ignore CGLIB subclasses - introspect the actual user class.
	Class<?> userClass = ClassUtils.getUserClass(targetClass);
	// The method may be on an interface, but we need attributes from the target class.
	// If the target class is null, the method will be unchanged.
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
	// If we are dealing with method with generic parameters, find the original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

	// First try is the method in the target class.
	TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
	if (txAttr != null) {
		return txAttr;
	}

	// Second try is the transaction attribute on the target class.
	txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
	if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
		return txAttr;
	}

	if (specificMethod != method) {
		// Fallback is to look at the original method.
		txAttr = findTransactionAttribute(method);
		if (txAttr != null) {
			return txAttr;
		}
		// Last fallback is the class of the original method.
		txAttr = findTransactionAttribute(method.getDeclaringClass());
		if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
			return txAttr;
		}
	}

	return null;
}
 
Example 17
Source File: DefaultAopMethodAuthorizeDefinitionParser.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
public CacheKey buildCacheKey(Class target, Method method) {
    return new CacheKey(ClassUtils.getUserClass(target), method);
}
 
Example 18
Source File: AopUtils.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Given a method, which may come from an interface, and a target class used
 * in the current AOP invocation, find the corresponding target method if there
 * is one. E.g. the method may be {@code IFoo.bar()} and the target class
 * may be {@code DefaultFoo}. In this case, the method may be
 * {@code DefaultFoo.bar()}. This enables attributes on that method to be found.
 * <p><b>NOTE:</b> In contrast to {@link org.springframework.util.ClassUtils#getMostSpecificMethod},
 * this method resolves Java 5 bridge methods in order to retrieve attributes
 * from the <i>original</i> method definition.
 * @param method the method to be invoked, which may come from an interface
 * @param targetClass the target class for the current invocation.
 * May be {@code null} or may not even implement the method.
 * @return the specific target method, or the original method if the
 * {@code targetClass} doesn't implement it or is {@code null}
 * @see org.springframework.util.ClassUtils#getMostSpecificMethod
 */
public static Method getMostSpecificMethod(Method method, @Nullable Class<?> targetClass) {
	Class<?> specificTargetClass = (targetClass != null ? ClassUtils.getUserClass(targetClass) : null);
	Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, specificTargetClass);
	// If we are dealing with method with generic parameters, find the original method.
	return BridgeMethodResolver.findBridgedMethod(resolvedMethod);
}
 
Example 19
Source File: JmxUtils.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Return the class or interface to expose for the given bean.
 * This is the class that will be searched for attributes and operations
 * (for example, checked for annotations).
 * <p>This implementation returns the superclass for a CGLIB proxy and
 * the class of the given bean else (for a JDK proxy or a plain bean class).
 * @param managedBean the bean instance (might be an AOP proxy)
 * @return the bean class to expose
 * @see org.springframework.util.ClassUtils#getUserClass(Object)
 */
public static Class<?> getClassToExpose(Object managedBean) {
	return ClassUtils.getUserClass(managedBean);
}
 
Example 20
Source File: JmxUtils.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return the class or interface to expose for the given bean class.
 * This is the class that will be searched for attributes and operations
 * (for example, checked for annotations).
 * <p>This implementation returns the superclass for a CGLIB proxy and
 * the class of the given bean else (for a JDK proxy or a plain bean class).
 * @param clazz the bean class (might be an AOP proxy class)
 * @return the bean class to expose
 * @see org.springframework.util.ClassUtils#getUserClass(Class)
 */
public static Class<?> getClassToExpose(Class<?> clazz) {
	return ClassUtils.getUserClass(clazz);
}