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

The following examples show how to use org.springframework.util.ClassUtils#isAssignable() . 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: ControllerAdviceBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check whether the given bean type should be assisted by this
 * {@code @ControllerAdvice} instance.
 * @param beanType the type of the bean to check
 * @see org.springframework.web.bind.annotation.ControllerAdvice
 * @since 4.0
 */
public boolean isApplicableToBeanType(Class<?> beanType) {
	if (!hasSelectors()) {
		return true;
	}
	else if (beanType != null) {
		for (String basePackage : this.basePackages) {
			if (beanType.getName().startsWith(basePackage)) {
				return true;
			}
		}
		for (Class<?> clazz : this.assignableTypes) {
			if (ClassUtils.isAssignable(clazz, beanType)) {
				return true;
			}
		}
		for (Class<? extends Annotation> annotationClass : this.annotations) {
			if (AnnotationUtils.findAnnotation(beanType, annotationClass) != null) {
				return true;
			}
		}
	}
	return false;
}
 
Example 2
Source File: WebUtils.java    From spring-webmvc-support with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Find the {@link Map map} of {@link Registration} in specified {@link Class}
 *
 * @param servletContext   {@link ServletContext}
 * @param registrationsMap the {@link Map map} of {@link Registration}
 * @param targetClass      the target {@link Class}
 * @param <R>              the subtype of {@link Registration}
 * @return the unmodifiable {@link Map map} of {@link Registration} i
 */
protected static <R extends Registration> Map<String, R> findRegistrations(
        ServletContext servletContext, Map<String, R> registrationsMap, Class<?> targetClass) {

    if (registrationsMap.isEmpty()) {
        return Collections.emptyMap();
    }

    ClassLoader classLoader = servletContext.getClassLoader();

    Map<String, R> foundRegistrationsMap = new LinkedHashMap<String, R>();

    for (Map.Entry<String, R> entry : registrationsMap.entrySet()) {
        R registration = entry.getValue();
        String className = registration.getClassName();
        Class<?> registeredRegistrationClass = ClassUtils.resolveClassName(className, classLoader);
        if (ClassUtils.isAssignable(targetClass, registeredRegistrationClass)) {
            String servletName = entry.getKey();
            foundRegistrationsMap.put(servletName, registration);
        }
    }

    return Collections.unmodifiableMap(foundRegistrationsMap);

}
 
Example 3
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 4
Source File: DefaultPredicateArgumentResolver.java    From java-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains the domain type information from the given method parameter. Will
 * favor an explicitly registered on through
 * {@link QuerydslPredicate#root()} but use the actual type of the method's
 * return type as fallback.
 * 
 * @param parameter
 *            must not be {@literal null}.
 * @return
 */
static TypeInformation<?> extractTypeInfo(MethodParameter parameter) {

	QuerydslPredicate annotation = parameter.getParameterAnnotation(QuerydslPredicate.class);

	if (annotation != null && !Object.class.equals(annotation.root())) {
		return ClassTypeInformation.from(annotation.root());
	}

	Class<?> containingClass = parameter.getContainingClass();
	if (ClassUtils.isAssignable(EntityController.class, containingClass)) {
		ResolvableType resolvableType = ResolvableType.forClass(containingClass);
		return ClassTypeInformation.from(resolvableType.as(EntityController.class).getGeneric(0).resolve());
	}

	return detectDomainType(ClassTypeInformation.fromReturnTypeOf(parameter.getMethod()));
}
 
Example 5
Source File: PropertyEditorRegistrySupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private PropertyEditor getPropertyEditor(Class<?> requiredType) {
	// Special case: If no required type specified, which usually only happens for
	// Collection elements, or required type is not assignable to registered type,
	// which usually only happens for generic properties of type Object -
	// then return PropertyEditor if not registered for Collection or array type.
	// (If not registered for Collection or array, it is assumed to be intended
	// for elements.)
	if (this.registeredType == null ||
			(requiredType != null &&
			(ClassUtils.isAssignable(this.registeredType, requiredType) ||
			ClassUtils.isAssignable(requiredType, this.registeredType))) ||
			(requiredType == null &&
			(!Collection.class.isAssignableFrom(this.registeredType) && !this.registeredType.isArray()))) {
		return this.propertyEditor;
	}
	else {
		return null;
	}
}
 
Example 6
Source File: PropertyEditorRegistrySupport.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
private PropertyEditor getPropertyEditor(Class<?> requiredType) {
	// Special case: If no required type specified, which usually only happens for
	// Collection elements, or required type is not assignable to registered type,
	// which usually only happens for generic properties of type Object -
	// then return PropertyEditor if not registered for Collection or array type.
	// (If not registered for Collection or array, it is assumed to be intended
	// for elements.)
	if (this.registeredType == null ||
			(requiredType != null &&
			(ClassUtils.isAssignable(this.registeredType, requiredType) ||
			ClassUtils.isAssignable(requiredType, this.registeredType))) ||
			(requiredType == null &&
			(!Collection.class.isAssignableFrom(this.registeredType) && !this.registeredType.isArray()))) {
		return this.propertyEditor;
	}
	else {
		return null;
	}
}
 
Example 7
Source File: AbstractDynamoDBQueryCriteria.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <P> List<P> getAttributeValueAsList(Object attributeValue) {
	boolean isIterable = ClassUtils.isAssignable(Iterable.class, attributeValue.getClass());
	List<P> attributeValueAsList = null;
	if (isIterable) {
		attributeValueAsList = new ArrayList<P>();
		Iterable<P> iterable = (Iterable<P>) attributeValue;
		for (P attributeValueElement : iterable) {
			attributeValueAsList.add(attributeValueElement);
		}
		return attributeValueAsList;
	}
	return null;
}
 
Example 8
Source File: ObjectToObjectConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static boolean isApplicable(Member member, Class<?> sourceClass) {
	if (member instanceof Method) {
		Method method = (Method) member;
		return (!Modifier.isStatic(method.getModifiers()) ?
				ClassUtils.isAssignable(method.getDeclaringClass(), sourceClass) :
				method.getParameterTypes()[0] == sourceClass);
	}
	else if (member instanceof Constructor) {
		Constructor<?> ctor = (Constructor) member;
		return (ctor.getParameterTypes()[0] == sourceClass);
	}
	else {
		return false;
	}
}
 
Example 9
Source File: AbstractSolrQuery.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private Object countOrGetDocumentsForDelete(Query query) {

			Object result = null;

			if (solrQueryMethod.isCollectionQuery()) {
				Query clone = SimpleQuery.fromQuery(query);
				result = solrOperations.queryForPage(clone.setPageRequest(new SolrPageRequest(0, Integer.MAX_VALUE)),
						solrQueryMethod.getEntityInformation().getJavaType()).getContent();
			}

			if (ClassUtils.isAssignable(Number.class, solrQueryMethod.getReturnedObjectType())) {
				result = solrOperations.count(query);
			}
			return result;
		}
 
Example 10
Source File: QueueMessageHandler.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private boolean hasNoAcknowledgmentParameter(Class<?>[] parameterTypes) {
	for (Class<?> parameterType : parameterTypes) {
		if (ClassUtils.isAssignable(Acknowledgment.class, parameterType)) {
			return false;
		}
	}

	return true;
}
 
Example 11
Source File: AspectJAfterReturningAdvice.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Following AspectJ semantics, if a return value is null (or return type is void),
 * then the return type of target method should be used to determine whether advice
 * is invoked or not. Also, even if the return type is void, if the type of argument
 * declared in the advice method is Object, then the advice must still get invoked.
 * @param type the type of argument declared in advice method
 * @param method the advice method
 * @param returnValue the return value of the target method
 * @return whether to invoke the advice method for the given return value and type
 */
private boolean matchesReturnValue(Class<?> type, Method method, @Nullable Object returnValue) {
	if (returnValue != null) {
		return ClassUtils.isAssignableValue(type, returnValue);
	}
	else if (Object.class == type && void.class == method.getReturnType()) {
		return true;
	}
	else {
		return ClassUtils.isAssignable(type, method.getReturnType());
	}
}
 
Example 12
Source File: ObjectToObjectConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static boolean isApplicable(Member member, Class<?> sourceClass) {
	if (member instanceof Method) {
		Method method = (Method) member;
		return (!Modifier.isStatic(method.getModifiers()) ?
				ClassUtils.isAssignable(method.getDeclaringClass(), sourceClass) :
				method.getParameterTypes()[0] == sourceClass);
	}
	else if (member instanceof Constructor) {
		Constructor<?> ctor = (Constructor<?>) member;
		return (ctor.getParameterTypes()[0] == sourceClass);
	}
	else {
		return false;
	}
}
 
Example 13
Source File: ReflectionHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Based on {@link MethodInvoker#getTypeDifferenceWeight(Class[], Object[])} but operates on TypeDescriptors.
 */
public static int getTypeDifferenceWeight(List<TypeDescriptor> paramTypes, List<TypeDescriptor> argTypes) {
	int result = 0;
	for (int i = 0; i < paramTypes.size(); i++) {
		TypeDescriptor paramType = paramTypes.get(i);
		TypeDescriptor argType = (i < argTypes.size() ? argTypes.get(i) : null);
		if (argType == null) {
			if (paramType.isPrimitive()) {
				return Integer.MAX_VALUE;
			}
		}
		else {
			Class<?> paramTypeClazz = paramType.getType();
			if (!ClassUtils.isAssignable(paramTypeClazz, argType.getType())) {
				return Integer.MAX_VALUE;
			}
			if (paramTypeClazz.isPrimitive()) {
				paramTypeClazz = Object.class;
			}
			Class<?> superClass = argType.getType().getSuperclass();
			while (superClass != null) {
				if (paramTypeClazz.equals(superClass)) {
					result = result + 2;
					superClass = null;
				}
				else if (ClassUtils.isAssignable(paramTypeClazz, superClass)) {
					result = result + 2;
					superClass = superClass.getSuperclass();
				}
				else {
					superClass = null;
				}
			}
			if (paramTypeClazz.isInterface()) {
				result = result + 1;
			}
		}
	}
	return result;
}
 
Example 14
Source File: ObjectToObjectConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static Method determineToMethod(Class<?> targetClass, Class<?> sourceClass) {
	if (String.class == targetClass || String.class == sourceClass) {
		// Do not accept a toString() method or any to methods on String itself
		return null;
	}

	Method method = ClassUtils.getMethodIfAvailable(sourceClass, "to" + targetClass.getSimpleName());
	return (method != null && !Modifier.isStatic(method.getModifiers()) &&
			ClassUtils.isAssignable(targetClass, method.getReturnType()) ? method : null);
}
 
Example 15
Source File: ObjectToObjectConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static Method determineToMethod(Class<?> targetClass, Class<?> sourceClass) {
	if (String.class == targetClass || String.class == sourceClass) {
		// Do not accept a toString() method or any to methods on String itself
		return null;
	}

	Method method = ClassUtils.getMethodIfAvailable(sourceClass, "to" + targetClass.getSimpleName());
	return (method != null && !Modifier.isStatic(method.getModifiers()) &&
			ClassUtils.isAssignable(targetClass, method.getReturnType()) ? method : null);
}
 
Example 16
Source File: AspectJAfterReturningAdvice.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Following AspectJ semantics, if a return value is null (or return type is void),
 * then the return type of target method should be used to determine whether advice
 * is invoked or not. Also, even if the return type is void, if the type of argument
 * declared in the advice method is Object, then the advice must still get invoked.
 * @param type the type of argument declared in advice method
 * @param method the advice method
 * @param returnValue the return value of the target method
 * @return whether to invoke the advice method for the given return value and type
 */
private boolean matchesReturnValue(Class<?> type, Method method, Object returnValue) {
	if (returnValue != null) {
		return ClassUtils.isAssignableValue(type, returnValue);
	}
	else if (Object.class == type && void.class == method.getReturnType()) {
		return true;
	}
	else {
		return ClassUtils.isAssignable(type, method.getReturnType());
	}
}
 
Example 17
Source File: NotificationSubjectHandlerMethodArgumentResolver.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	return (parameter.hasParameterAnnotation(NotificationSubject.class)
			&& ClassUtils.isAssignable(String.class, parameter.getParameterType()));
}
 
Example 18
Source File: BeanUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Copy the property values of the given source bean into the given target bean.
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
		throws BeansException {

	Assert.notNull(source, "Source must not be null");
	Assert.notNull(target, "Target must not be null");

	Class<?> actualEditable = target.getClass();
	if (editable != null) {
		if (!editable.isInstance(target)) {
			throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
					"] not assignable to Editable class [" + editable.getName() + "]");
		}
		actualEditable = editable;
	}
	PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
	List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

	for (PropertyDescriptor targetPd : targetPds) {
		Method writeMethod = targetPd.getWriteMethod();
		if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
			PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
			if (sourcePd != null) {
				Method readMethod = sourcePd.getReadMethod();
				if (readMethod != null &&
						ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
					try {
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
							writeMethod.setAccessible(true);
						}
						writeMethod.invoke(target, value);
					}
					catch (Throwable ex) {
						throw new FatalBeanException(
								"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
					}
				}
			}
		}
	}
}
 
Example 19
Source File: AbstractBeanFactory.java    From blog_demos with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isTypeMatch(String name, Class<?> targetType) throws NoSuchBeanDefinitionException {
	String beanName = transformedBeanName(name);
	Class<?> typeToMatch = (targetType != null ? targetType : Object.class);

	// Check manually registered singletons.
	Object beanInstance = getSingleton(beanName, false);
	if (beanInstance != null) {
		if (beanInstance instanceof FactoryBean) {
			if (!BeanFactoryUtils.isFactoryDereference(name)) {
				Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
				return (type != null && ClassUtils.isAssignable(typeToMatch, type));
			}
			else {
				return ClassUtils.isAssignableValue(typeToMatch, beanInstance);
			}
		}
		else {
			return !BeanFactoryUtils.isFactoryDereference(name) &&
					ClassUtils.isAssignableValue(typeToMatch, beanInstance);
		}
	}
	else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
		// null instance registered
		return false;
	}

	else {
		// No singleton instance found -> check bean definition.
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// No bean definition found in this factory -> delegate to parent.
			return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType);
		}

		// Retrieve corresponding bean definition.
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

		Class<?>[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ?
				new Class<?>[] {typeToMatch} : new Class<?>[] {FactoryBean.class, typeToMatch});

		// Check decorated bean definition, if any: We assume it'll be easier
		// to determine the decorated bean's type than the proxy's type.
		BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
		if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
			RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
			Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
			if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
				return typeToMatch.isAssignableFrom(targetClass);
			}
		}

		Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);
		if (beanType == null) {
			return false;
		}

		// Check bean class whether we're dealing with a FactoryBean.
		if (FactoryBean.class.isAssignableFrom(beanType)) {
			if (!BeanFactoryUtils.isFactoryDereference(name)) {
				// If it's a FactoryBean, we want to look at what it creates, not the factory class.
				beanType = getTypeForFactoryBean(beanName, mbd);
				if (beanType == null) {
					return false;
				}
			}
		}
		else if (BeanFactoryUtils.isFactoryDereference(name)) {
			// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
			// type but we nevertheless are being asked to dereference a FactoryBean...
			// Let's check the original bean class and proceed with it if it is a FactoryBean.
			beanType = predictBeanType(beanName, mbd, FactoryBean.class);
			if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {
				return false;
			}
		}

		return typeToMatch.isAssignableFrom(beanType);
	}
}
 
Example 20
Source File: NotificationSubjectArgumentResolver.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	return (parameter.hasParameterAnnotation(NotificationSubject.class)
			&& ClassUtils.isAssignable(String.class, parameter.getParameterType()));
}