Java Code Examples for org.springframework.core.ResolvableType#forType()

The following examples show how to use org.springframework.core.ResolvableType#forType() . 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: FastJsonHttpMessageConverter.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private static ResolvableType resolveVariable(TypeVariable<?> typeVariable, ResolvableType contextType) {
    ResolvableType resolvedType;
    if (contextType.hasGenerics()) {
        resolvedType = ResolvableType.forType(typeVariable, contextType);
        if (resolvedType.resolve() != null) {
            return resolvedType;
        }
    }

    ResolvableType superType = contextType.getSuperType();
    if (superType != ResolvableType.NONE) {
        resolvedType = resolveVariable(typeVariable, superType);
        if (resolvedType.resolve() != null) {
            return resolvedType;
        }
    }
    for (ResolvableType ifc : contextType.getInterfaces()) {
        resolvedType = resolveVariable(typeVariable, ifc);
        if (resolvedType.resolve() != null) {
            return resolvedType;
        }
    }
    return ResolvableType.NONE;
}
 
Example 2
Source File: FunctionTypeUtils.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
public static Type compose(Type originType, Type composedType) {
	ResolvableType resolvableOriginType = ResolvableType.forType(originType);
	ResolvableType resolvableComposedType = ResolvableType.forType(composedType);
	if (FunctionTypeUtils.isSupplier(originType)) {
		if (FunctionTypeUtils.isFunction(composedType)) {
			ResolvableType resolvableLastArgument = resolvableComposedType.getGenerics()[1];
			resolvableLastArgument = FunctionTypeUtils.isPublisher(resolvableOriginType.getGeneric(0).getType())
					? ResolvableType.forClassWithGenerics(resolvableOriginType.getGeneric(0).getRawClass(), resolvableLastArgument)
							: resolvableLastArgument;
					originType = ResolvableType.forClassWithGenerics(Supplier.class, resolvableLastArgument).getType();
		}
	}
	else  {
		ResolvableType outType = FunctionTypeUtils.isConsumer(composedType)
				? ResolvableType.forClass(Void.class)
						: (ObjectUtils.isEmpty(resolvableComposedType.getGenerics())
								? ResolvableType.forClass(Object.class) : resolvableComposedType.getGenerics()[1]);

		originType = ResolvableType.forClassWithGenerics(Function.class,
				ObjectUtils.isEmpty(resolvableOriginType.getGenerics()) ? resolvableOriginType : resolvableOriginType.getGenerics()[0],
						outType).getType();
	}
	return originType;
}
 
Example 3
Source File: AbstractMediaTypeExpressionTest.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
protected T createExpression(String expression) {
	ResolvableType resolvableType = ResolvableType
			.forType(getClass().getGenericSuperclass());
	Class<T> firstGenericType = (Class<T>) resolvableType.resolveGeneric(0);
	Constructor<T> constructor = null;
	try {
		constructor = firstGenericType.getDeclaredConstructor(String.class);
	}
	catch (NoSuchMethodException e) {
		throw new RuntimeException(e);
	}
	return BeanUtils.instantiateClass(constructor, expression);
}
 
Example 4
Source File: ReturnTypeParser.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * This is a copy of GenericTypeResolver.resolveType which is not available on spring 4.
 * This also keeps compatibility with spring-boot 1 applications.
 * Resolve the given generic type against the given context class,
 * substituting type variables as far as possible.
 * @param genericType the (potentially) generic type
 * @param contextClass a context class for the target type, for example a class in which the target type appears in a method signature (can be {@code null})
 * @return the resolved type (possibly the given generic type as-is)
 * @since 5.0
 */
static Type resolveType(Type genericType, @Nullable Class<?> contextClass) {
	if (contextClass != null) {
		if (genericType instanceof TypeVariable) {
			ResolvableType resolvedTypeVariable = resolveVariable(
					(TypeVariable<?>) genericType, ResolvableType.forClass(contextClass));
			if (resolvedTypeVariable != ResolvableType.NONE) {
				Class<?> resolved = resolvedTypeVariable.resolve();
				if (resolved != null) {
					return resolved;
				}
			}
		}
		else if (genericType instanceof ParameterizedType) {
			ResolvableType resolvedType = ResolvableType.forType(genericType);
			if (resolvedType.hasUnresolvableGenerics()) {
				ParameterizedType parameterizedType = (ParameterizedType) genericType;
				Class<?>[] generics = new Class<?>[parameterizedType.getActualTypeArguments().length];
				Type[] typeArguments = parameterizedType.getActualTypeArguments();
				ResolvableType contextType = ResolvableType.forClass(contextClass);
				findTypeForGenerics(generics, typeArguments, contextType);
				Class<?> rawClass = resolvedType.getRawClass();
				if (rawClass != null) {
					return ResolvableType.forClassWithGenerics(rawClass, generics).getType();
				}
			}
		}
	}
	return genericType;
}
 
Example 5
Source File: RestMethodMetadata.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private String getClassName(Type type) {
	if (type == null) {
		return null;
	}
	ResolvableType resolvableType = ResolvableType.forType(type);
	return resolvableType.resolve().getName();
}
 
Example 6
Source File: GenericApplicationListenerAdapterTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void genericListenerStrictTypeEventSubTypeNotMatching() {
	LongEvent stringEvent = new LongEvent(this, 123L);
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(false, StringEventListener.class, eventType);
}
 
Example 7
Source File: MultipartBodyBuilder.java    From java-technology-stack with MIT License 4 votes vote down vote up
public PublisherPartBuilder(HttpHeaders headers, P body, ParameterizedTypeReference<S> typeReference) {
	super(headers, body);
	this.resolvableType = ResolvableType.forType(typeReference);
}
 
Example 8
Source File: HttpMessageConverterExtractor.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings({"unchecked", "rawtypes", "resource"})
public T extractData(ClientHttpResponse response) throws IOException {
	MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
	if (!responseWrapper.hasMessageBody() || responseWrapper.hasEmptyMessageBody()) {
		return null;
	}
	MediaType contentType = getContentType(responseWrapper);

	try {
		for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
			if (messageConverter instanceof GenericHttpMessageConverter) {
				GenericHttpMessageConverter<?> genericMessageConverter =
						(GenericHttpMessageConverter<?>) messageConverter;
				if (genericMessageConverter.canRead(this.responseType, null, contentType)) {
					if (logger.isDebugEnabled()) {
						ResolvableType resolvableType = ResolvableType.forType(this.responseType);
						logger.debug("Reading to [" + resolvableType + "]");
					}
					return (T) genericMessageConverter.read(this.responseType, null, responseWrapper);
				}
			}
			if (this.responseClass != null) {
				if (messageConverter.canRead(this.responseClass, contentType)) {
					if (logger.isDebugEnabled()) {
						String className = this.responseClass.getName();
						logger.debug("Reading to [" + className + "] as \"" + contentType + "\"");
					}
					return (T) messageConverter.read((Class) this.responseClass, responseWrapper);
				}
			}
		}
	}
	catch (IOException | HttpMessageNotReadableException ex) {
		throw new RestClientException("Error while extracting response for type [" +
				this.responseType + "] and content type [" + contentType + "]", ex);
	}

	throw new RestClientException("Could not extract response: no suitable HttpMessageConverter found " +
			"for response type [" + this.responseType + "] and content type [" + contentType + "]");
}
 
Example 9
Source File: GenericApplicationListenerAdapterTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test  // Demonstrates we cant inject that event because the listener has a raw type
public void genericListenerRawTypeTypeErasure() {
	GenericTestEvent<String> stringEvent = createGenericTestEvent("test");
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(true, RawApplicationListener.class, eventType);
}
 
Example 10
Source File: GenericApplicationListenerAdapterTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void genericListenerStrictTypeNotMatchTypeErasure() {
	GenericTestEvent<Long> longEvent = createGenericTestEvent(123L);
	ResolvableType eventType = ResolvableType.forType(longEvent.getClass());
	supportsEventType(false, StringEventListener.class, eventType);
}
 
Example 11
Source File: GenericApplicationListenerAdapterTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void genericListenerStrictTypeEventSubTypeNotMatching() {
	LongEvent stringEvent = new LongEvent(this, 123L);
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(false, StringEventListener.class, eventType);
}
 
Example 12
Source File: GenericApplicationListenerAdapterTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test // Demonstrates we can't inject that event because the generic type is lost
public void genericListenerStrictTypeTypeErasure() {
	GenericTestEvent<String> stringEvent = createGenericTestEvent("test");
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(false, StringEventListener.class, eventType);
}
 
Example 13
Source File: GenericApplicationListenerAdapterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test // Demonstrates we can't inject that event because the generic type is lost
public void genericListenerStrictTypeTypeErasure() {
	GenericTestEvent<String> stringEvent = createGenericTestEvent("test");
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(false, StringEventListener.class, eventType);
}
 
Example 14
Source File: MultipartBodyBuilder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public PublisherPartBuilder(HttpHeaders headers, P body, ParameterizedTypeReference<S> typeReference) {
	super(headers, body);
	this.resolvableType = ResolvableType.forType(typeReference);
}
 
Example 15
Source File: GenericsUtils.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
/**
 * For a specific class that implements or extends a parameterized type, return the
 * parameter of that interface at a given position. For example, for this class:
 *
 * <pre> {@code
 * class MessageChannelBinder implements Binder<MessageChannel, ?, ?>
 * } </pre>
 *
 * <pre> {@code
 * getParameterType(MessageChannelBinder.class, Binder.class, 0);
 * } </pre>
 *
 * will return {@code Binder}
 * @param evaluatedClass the evaluated class
 * @param interfaceClass the parametrized interface
 * @param position the position
 * @return the parameter type if any
 * @throws IllegalStateException if the evaluated class does not implement the
 * interface or
 */
public static Class<?> getParameterType(Class<?> evaluatedClass,
		Class<?> interfaceClass, int position) {
	Class<?> bindableType = null;
	Assert.isTrue(interfaceClass.isInterface(),
			"'interfaceClass' must be an interface");
	if (!interfaceClass.isAssignableFrom(evaluatedClass)) {
		throw new IllegalStateException(
				evaluatedClass + " does not implement " + interfaceClass);
	}
	ResolvableType currentType = ResolvableType.forType(evaluatedClass);
	while (!Object.class.equals(currentType.getRawClass()) && bindableType == null) {
		ResolvableType[] interfaces = currentType.getInterfaces();
		ResolvableType resolvableType = null;
		for (ResolvableType interfaceType : interfaces) {
			if (interfaceClass.equals(interfaceType.getRawClass())) {
				resolvableType = interfaceType;
				break;
			}
		}
		if (resolvableType == null) {
			currentType = currentType.getSuperType();
		}
		else {
			ResolvableType[] generics = resolvableType.getGenerics();
			ResolvableType generic = generics[position];
			Class<?> resolvedParameter = generic.resolve();
			if (resolvedParameter != null) {
				bindableType = resolvedParameter;
			}
			else {
				bindableType = Object.class;
			}
		}
	}
	if (bindableType == null) {
		throw new IllegalStateException(
				"Cannot find parameter of " + evaluatedClass.getName() + " for "
						+ interfaceClass + " at position " + position);
	}
	return bindableType;
}
 
Example 16
Source File: GenericApplicationListenerAdapterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test  // Demonstrates we cant inject that event because the listener has a raw type
public void genericListenerRawTypeTypeErasure() {
	GenericTestEvent<String> stringEvent = createGenericTestEvent("test");
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(true, RawApplicationListener.class, eventType);
}
 
Example 17
Source File: GenericApplicationListenerAdapterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void genericListenerStrictTypeNotMatchTypeErasure() {
	GenericTestEvent<Long> longEvent = createGenericTestEvent(123L);
	ResolvableType eventType = ResolvableType.forType(longEvent.getClass());
	supportsEventType(false, StringEventListener.class, eventType);
}
 
Example 18
Source File: GenericApplicationListenerAdapterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void genericListenerStrictTypeEventSubTypeNotMatching() {
	LongEvent stringEvent = new LongEvent(this, 123L);
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(false, StringEventListener.class, eventType);
}
 
Example 19
Source File: GenericApplicationListenerAdapterTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test // Demonstrates it works if we actually use the subtype
public void genericListenerStrictTypeEventSubType() {
	StringEvent stringEvent = new StringEvent(this, "test");
	ResolvableType eventType = ResolvableType.forType(stringEvent.getClass());
	supportsEventType(true, StringEventListener.class, eventType);
}
 
Example 20
Source File: TypeDescriptor.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Narrows this {@link TypeDescriptor} by setting its type to the class of the
 * provided value.
 * <p>If the value is {@code null}, no narrowing is performed and this TypeDescriptor
 * is returned unchanged.
 * <p>Designed to be called by binding frameworks when they read property, field,
 * or method return values. Allows such frameworks to narrow a TypeDescriptor built
 * from a declared property, field, or method return value type. For example, a field
 * declared as {@code java.lang.Object} would be narrowed to {@code java.util.HashMap}
 * if it was set to a {@code java.util.HashMap} value. The narrowed TypeDescriptor
 * can then be used to convert the HashMap to some other type. Annotation and nested
 * type context is preserved by the narrowed copy.
 * @param value the value to use for narrowing this type descriptor
 * @return this TypeDescriptor narrowed (returns a copy with its type updated to the
 * class of the provided value)
 */
public TypeDescriptor narrow(@Nullable Object value) {
	if (value == null) {
		return this;
	}
	ResolvableType narrowed = ResolvableType.forType(value.getClass(), getResolvableType());
	return new TypeDescriptor(narrowed, value.getClass(), getAnnotations());
}