org.springframework.core.GenericTypeResolver Java Examples

The following examples show how to use org.springframework.core.GenericTypeResolver. 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: ContextLoader.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
			determineContextInitializerClasses(sc);

	for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(this.contextInitializers);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
		initializer.initialize(wac);
	}
}
 
Example #2
Source File: GenericTypeResolverDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws NoSuchMethodException {

        // String 是 Comparable<String> 具体化
        displayReturnTypeGenericInfo(GenericTypeResolverDemo.class, Comparable.class, "getString");

        // ArrayList<Object> 是 List 泛型参数类型的具体化
        displayReturnTypeGenericInfo(GenericTypeResolverDemo.class, List.class, "getList");

        // StringList 也是 List 泛型参数类型的具体化
        displayReturnTypeGenericInfo(GenericTypeResolverDemo.class, List.class, "getStringList");

        // 具备 ParameterizedType 返回,否则 null

        // TypeVariable
        Map<TypeVariable, Type> typeVariableMap = GenericTypeResolver.getTypeVariableMap(StringList.class);
        System.out.println(typeVariableMap);
    }
 
Example #3
Source File: AnnotationMethodHandlerExceptionResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
		NativeWebRequest webRequest, Exception thrownException) throws Exception {

	Class<?>[] paramTypes = handlerMethod.getParameterTypes();
	Object[] args = new Object[paramTypes.length];
	Class<?> handlerType = handler.getClass();
	for (int i = 0; i < args.length; i++) {
		MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
		GenericTypeResolver.resolveParameterType(methodParam, handlerType);
		Class<?> paramType = methodParam.getParameterType();
		Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
		if (argValue != WebArgumentResolver.UNRESOLVED) {
			args[i] = argValue;
		}
		else {
			throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
					"] for @ExceptionHandler method: " + handlerMethod);
		}
	}
	return args;
}
 
Example #4
Source File: FrameworkServlet.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (ClassNotFoundException ex) {
		throw new ApplicationContextException(String.format("Could not load class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example #5
Source File: ContextLoader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
			determineContextInitializerClasses(sc);

	for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(this.contextInitializers);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
		initializer.initialize(wac);
	}
}
 
Example #6
Source File: AnnotationMethodHandlerExceptionResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
 */
private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
		NativeWebRequest webRequest, Exception thrownException) throws Exception {

	Class<?>[] paramTypes = handlerMethod.getParameterTypes();
	Object[] args = new Object[paramTypes.length];
	Class<?> handlerType = handler.getClass();
	for (int i = 0; i < args.length; i++) {
		MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
		GenericTypeResolver.resolveParameterType(methodParam, handlerType);
		Class<?> paramType = methodParam.getParameterType();
		Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
		if (argValue != WebArgumentResolver.UNRESOLVED) {
			args[i] = argValue;
		}
		else {
			throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
					"] for @ExceptionHandler method: " + handlerMethod);
		}
	}
	return args;
}
 
Example #7
Source File: HeaderMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
public void setup() {
	@SuppressWarnings("resource")
	GenericApplicationContext cxt = new GenericApplicationContext();
	cxt.refresh();
	this.resolver = new HeaderMethodArgumentResolver(new DefaultConversionService(), cxt.getBeanFactory());

	Method method = ReflectionUtils.findMethod(getClass(), "handleMessage", (Class<?>[]) null);
	this.paramRequired = new SynthesizingMethodParameter(method, 0);
	this.paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 1);
	this.paramSystemPropertyDefaultValue = new SynthesizingMethodParameter(method, 2);
	this.paramSystemPropertyName = new SynthesizingMethodParameter(method, 3);
	this.paramNotAnnotated = new SynthesizingMethodParameter(method, 4);
	this.paramOptional = new SynthesizingMethodParameter(method, 5);
	this.paramNativeHeader = new SynthesizingMethodParameter(method, 6);

	this.paramRequired.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
	GenericTypeResolver.resolveParameterType(this.paramRequired, HeaderMethodArgumentResolver.class);
}
 
Example #8
Source File: AdviceModeImportSelector.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This implementation resolves the type of annotation from generic metadata and
 * validates that (a) the annotation is in fact present on the importing
 * {@code @Configuration} class and (b) that the given annotation has an
 * {@linkplain #getAdviceModeAttributeName() advice mode attribute} of type
 * {@link AdviceMode}.
 * <p>The {@link #selectImports(AdviceMode)} method is then invoked, allowing the
 * concrete implementation to choose imports in a safe and convenient fashion.
 * @throws IllegalArgumentException if expected annotation {@code A} is not present
 * on the importing {@code @Configuration} class or if {@link #selectImports(AdviceMode)}
 * returns {@code null}
 */
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
	Class<?> annoType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
	AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
	if (attributes == null) {
		throw new IllegalArgumentException(String.format(
			"@%s is not present on importing class '%s' as expected",
			annoType.getSimpleName(), importingClassMetadata.getClassName()));
	}

	AdviceMode adviceMode = attributes.getEnum(this.getAdviceModeAttributeName());
	String[] imports = selectImports(adviceMode);
	if (imports == null) {
		throw new IllegalArgumentException(String.format("Unknown AdviceMode: '%s'", adviceMode));
	}
	return imports;
}
 
Example #9
Source File: AdviceModeImportSelector.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * This implementation resolves the type of annotation from generic metadata and
 * validates that (a) the annotation is in fact present on the importing
 * {@code @Configuration} class and (b) that the given annotation has an
 * {@linkplain #getAdviceModeAttributeName() advice mode attribute} of type
 * {@link AdviceMode}.
 * <p>The {@link #selectImports(AdviceMode)} method is then invoked, allowing the
 * concrete implementation to choose imports in a safe and convenient fashion.
 * @throws IllegalArgumentException if expected annotation {@code A} is not present
 * on the importing {@code @Configuration} class or if {@link #selectImports(AdviceMode)}
 * returns {@code null}
 */
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
	Class<?> annType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
	Assert.state(annType != null, "Unresolvable type argument for AdviceModeImportSelector");

	AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
	if (attributes == null) {
		throw new IllegalArgumentException(String.format(
				"@%s is not present on importing class '%s' as expected",
				annType.getSimpleName(), importingClassMetadata.getClassName()));
	}

	AdviceMode adviceMode = attributes.getEnum(getAdviceModeAttributeName());
	String[] imports = selectImports(adviceMode);
	if (imports == null) {
		throw new IllegalArgumentException("Unknown AdviceMode: " + adviceMode);
	}
	return imports;
}
 
Example #10
Source File: BeanPropertiesMapper.java    From alfresco-mvc with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected BeanPropertiesMapper(final NamespaceService namespaceService, final DictionaryService dictionaryService,
		final BeanPropertiesMapperConfigurer<T> configurer, final boolean reportNamespaceException) {
	Assert.notNull(namespaceService, "[Assertion failed] - the namespaceService argument must be null");
	Assert.notNull(dictionaryService, "[Assertion failed] - the dictionaryService argument must be null");

	this.namespaceService = namespaceService;
	this.dictionaryService = dictionaryService;
	this.reportNamespaceException = reportNamespaceException;

	Class<T> mappedClass = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(),
			NodePropertiesMapper.class);
	if (mappedClass != null) {
		setMappedClass(mappedClass);
	}

	BeanPropertiesMapperConfigurer<T> confTmp = configurer;
	if (configurer == null) {
		if (this instanceof BeanPropertiesMapperConfigurer) {
			confTmp = ((BeanPropertiesMapperConfigurer<T>) this);
		}
	}

	this.configurer = confTmp;
}
 
Example #11
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (ClassNotFoundException ex) {
		throw new ApplicationContextException(String.format("Could not load class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example #12
Source File: CustomConversions.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private void registerConversion(Object converter) {
	Class<?> type = converter.getClass();
	boolean isWriting = type.isAnnotationPresent(WritingConverter.class);
	boolean isReading = type.isAnnotationPresent(ReadingConverter.class);

	if (!isReading && !isWriting) {
		isReading = true;
		isWriting = true;
	}

	if (converter instanceof GenericConverter) {
		GenericConverter genericConverter = (GenericConverter) converter;
		for (ConvertiblePair pair : genericConverter.getConvertibleTypes()) {
			register(new ConvertibleContext(pair, isReading, isWriting));
		}
	} else if (converter instanceof Converter) {
		Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class);
		register(new ConvertibleContext(arguments[0], arguments[1], isReading, isWriting));
	} else {
		throw new IllegalArgumentException(
				"Unsupported Converter type! Expected either GenericConverter if Converter.");
	}
}
 
Example #13
Source File: GenericTypeAwarePropertyDescriptor.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized Class<?> getPropertyType() {
	if (this.propertyType == null) {
		if (this.readMethod != null) {
			this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
		}
		else {
			MethodParameter writeMethodParam = getWriteMethodParameter();
			if (writeMethodParam != null) {
				this.propertyType = writeMethodParam.getParameterType();
			}
			else {
				this.propertyType = super.getPropertyType();
			}
		}
	}
	return this.propertyType;
}
 
Example #14
Source File: FrameworkServlet.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null) {
			Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
					"Could not add context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (Exception ex) {
		throw new IllegalArgumentException(String.format("Could not instantiate class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example #15
Source File: HeaderMethodArgumentResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
	@SuppressWarnings("resource")
	GenericApplicationContext cxt = new GenericApplicationContext();
	cxt.refresh();
	this.resolver = new HeaderMethodArgumentResolver(new DefaultConversionService(), cxt.getBeanFactory());

	Method method = getClass().getDeclaredMethod("handleMessage",
			String.class, String.class, String.class, String.class, String.class);
	this.paramRequired = new SynthesizingMethodParameter(method, 0);
	this.paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 1);
	this.paramSystemProperty = new SynthesizingMethodParameter(method, 2);
	this.paramNotAnnotated = new SynthesizingMethodParameter(method, 3);
	this.paramNativeHeader = new SynthesizingMethodParameter(method, 4);

	this.paramRequired.initParameterNameDiscovery(new DefaultParameterNameDiscoverer());
	GenericTypeResolver.resolveParameterType(this.paramRequired, HeaderMethodArgumentResolver.class);
}
 
Example #16
Source File: AdviceModeImportSelector.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation resolves the type of annotation from generic metadata and
 * validates that (a) the annotation is in fact present on the importing
 * {@code @Configuration} class and (b) that the given annotation has an
 * {@linkplain #getAdviceModeAttributeName() advice mode attribute} of type
 * {@link AdviceMode}.
 * <p>The {@link #selectImports(AdviceMode)} method is then invoked, allowing the
 * concrete implementation to choose imports in a safe and convenient fashion.
 * @throws IllegalArgumentException if expected annotation {@code A} is not present
 * on the importing {@code @Configuration} class or if {@link #selectImports(AdviceMode)}
 * returns {@code null}
 */
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
	Class<?> annType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
	Assert.state(annType != null, "Unresolvable type argument for AdviceModeImportSelector");

	AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
	if (attributes == null) {
		throw new IllegalArgumentException(String.format(
				"@%s is not present on importing class '%s' as expected",
				annType.getSimpleName(), importingClassMetadata.getClassName()));
	}

	AdviceMode adviceMode = attributes.getEnum(getAdviceModeAttributeName());
	String[] imports = selectImports(adviceMode);
	if (imports == null) {
		throw new IllegalArgumentException("Unknown AdviceMode: " + adviceMode);
	}
	return imports;
}
 
Example #17
Source File: SimpleIdentifiableRepresentationModelAssembler.java    From spring-hateoas-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Default a assembler based on Spring MVC controller, resource type, and {@link LinkRelationProvider}. With this
 * combination of information, resources can be defined.
 *
 * @see #setBasePath(String) to adjust base path to something like "/api"/
 * @param controllerClass - Spring MVC controller to base links off of
 * @param relProvider
 */
public SimpleIdentifiableRepresentationModelAssembler(Class<?> controllerClass, LinkRelationProvider relProvider) {

	this.controllerClass = controllerClass;
	this.relProvider = relProvider;

	// Find the "T" type contained in "T extends Identifiable<?>", e.g.
	// SimpleIdentifiableRepresentationModelAssembler<User> -> User
	this.resourceType = GenericTypeResolver.resolveTypeArgument(this.getClass(),
			SimpleIdentifiableRepresentationModelAssembler.class);
}
 
Example #18
Source File: InvocableHandlerMethod.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Get the method argument values for the current request.
 */
private Object[] getMethodArgumentValues(Message<?> message, Object... providedArgs) throws Exception {
	MethodParameter[] parameters = getMethodParameters();
	Object[] args = new Object[parameters.length];
	for (int i = 0; i < parameters.length; i++) {
		MethodParameter parameter = parameters[i];
		parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
		GenericTypeResolver.resolveParameterType(parameter, getBean().getClass());
		args[i] = resolveProvidedArgument(parameter, providedArgs);
		if (args[i] != null) {
			continue;
		}
		if (this.argumentResolvers.supportsParameter(parameter)) {
			try {
				args[i] = this.argumentResolvers.resolveArgument(parameter, message);
				continue;
			}
			catch (Exception ex) {
				if (logger.isDebugEnabled()) {
					logger.debug(getArgumentResolutionErrorMessage("Error resolving argument", i), ex);
				}
				throw ex;
			}
		}
		if (args[i] == null) {
			String msg = getArgumentResolutionErrorMessage("No suitable resolver for argument", i);
			throw new IllegalStateException(msg);
		}
	}
	return args;
}
 
Example #19
Source File: DependencyDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Optionally set the concrete class that contains this dependency.
 * This may differ from the class that declares the parameter/field in that
 * it may be a subclass thereof, potentially substituting type variables.
 * @since 4.0
 */
public void setContainingClass(Class<?> containingClass) {
	this.containingClass = containingClass;
	this.resolvableType = null;
	if (this.methodParameter != null) {
		GenericTypeResolver.resolveParameterType(this.methodParameter, containingClass);
	}
}
 
Example #20
Source File: FormattingConversionService.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static Class<? extends Annotation> getAnnotationType(AnnotationFormatterFactory<? extends Annotation> factory) {
	Class<? extends Annotation> annotationType = (Class<? extends Annotation>)
			GenericTypeResolver.resolveTypeArgument(factory.getClass(), AnnotationFormatterFactory.class);
	if (annotationType == null) {
		throw new IllegalArgumentException("Unable to extract parameterized Annotation type argument from " +
				"AnnotationFormatterFactory [" + factory.getClass().getName() +
				"]; does the factory parameterize the <A extends Annotation> generic type?");
	}
	return annotationType;
}
 
Example #21
Source File: ConstructorResolver.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve the prepared arguments stored in the given bean definition.
 */
private Object[] resolvePreparedArguments(
		String beanName, RootBeanDefinition mbd, BeanWrapper bw, Member methodOrCtor, Object[] argsToResolve) {

	Class<?>[] paramTypes = (methodOrCtor instanceof Method ?
			((Method) methodOrCtor).getParameterTypes() : ((Constructor<?>) methodOrCtor).getParameterTypes());
	TypeConverter converter = (this.beanFactory.getCustomTypeConverter() != null ?
			this.beanFactory.getCustomTypeConverter() : bw);
	BeanDefinitionValueResolver valueResolver =
			new BeanDefinitionValueResolver(this.beanFactory, beanName, mbd, converter);
	Object[] resolvedArgs = new Object[argsToResolve.length];
	for (int argIndex = 0; argIndex < argsToResolve.length; argIndex++) {
		Object argValue = argsToResolve[argIndex];
		MethodParameter methodParam = MethodParameter.forMethodOrConstructor(methodOrCtor, argIndex);
		GenericTypeResolver.resolveParameterType(methodParam, methodOrCtor.getDeclaringClass());
		if (argValue instanceof AutowiredArgumentMarker) {
			argValue = resolveAutowiredArgument(methodParam, beanName, null, converter);
		}
		else if (argValue instanceof BeanMetadataElement) {
			argValue = valueResolver.resolveValueIfNecessary("constructor argument", argValue);
		}
		else if (argValue instanceof String) {
			argValue = this.beanFactory.evaluateBeanDefinitionString((String) argValue, mbd);
		}
		Class<?> paramType = paramTypes[argIndex];
		try {
			resolvedArgs[argIndex] = converter.convertIfNecessary(argValue, paramType, methodParam);
		}
		catch (TypeMismatchException ex) {
			String methodType = (methodOrCtor instanceof Constructor ? "constructor" : "factory method");
			throw new UnsatisfiedDependencyException(
					mbd.getResourceDescription(), beanName, argIndex, paramType,
					"Could not convert " + methodType + " argument value of type [" +
					ObjectUtils.nullSafeClassName(argValue) +
					"] to required type [" + paramType.getName() + "]: " + ex.getMessage());
		}
	}
	return resolvedArgs;
}
 
Example #22
Source File: DependencyDescriptor.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Optionally set the concrete class that contains this dependency.
 * This may differ from the class that declares the parameter/field in that
 * it may be a subclass thereof, potentially substituting type variables.
 */
public void setContainingClass(Class<?> containingClass) {
	this.containingClass = containingClass;
	if (this.methodParameter != null) {
		GenericTypeResolver.resolveParameterType(this.methodParameter, containingClass);
	}
}
 
Example #23
Source File: MSF4JSpringApplication.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private void applyInitializers(ConfigurableApplicationContext context) {
    for (ApplicationContextInitializer initializer : getInitializers()) {
        Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
                initializer.getClass(), ApplicationContextInitializer.class);
        Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
        initializer.initialize(context);
    }
}
 
Example #24
Source File: FormattingConversionService.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
static Class<?> getFieldType(Formatter<?> formatter) {
	Class<?> fieldType = GenericTypeResolver.resolveTypeArgument(formatter.getClass(), Formatter.class);
	if (fieldType == null) {
		throw new IllegalArgumentException("Unable to extract parameterized field type argument from Formatter [" +
				formatter.getClass().getName() + "]; does the formatter parameterize the <T> generic type?");
	}
	return fieldType;
}
 
Example #25
Source File: JsonConverter.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable MediaType mediaType) {
	if (!canRead(mediaType)) {
		return false;
	}
	if (type == Result.class) {
		return false;
	}
	boolean hasContextClass = contextClass != null;
	Boolean cacheResult;
	if (hasContextClass) {
		cacheResult = contextDeserializeCache.get(StrUtil.concat(type.getTypeName(), contextClass.getName()));
	} else {
		cacheResult = noContextDeserializeCache.get(type);
	}
	if (cacheResult != null) {
		return cacheResult;
	}
	JavaType javaType = JSONUtil.mapper().getTypeFactory().constructType(GenericTypeResolver.resolveType(type, contextClass));
	AtomicReference<Throwable> causeRef = new AtomicReference<>();
	cacheResult = JSONUtil.mapper().canDeserialize(javaType, causeRef);
	logWarningIfNecessary(javaType, causeRef.get());
	if (hasContextClass) {
		contextDeserializeCache.put(StrUtil.concat(type.getTypeName(), contextClass.getName()), cacheResult);
	} else {
		noContextDeserializeCache.put(type, cacheResult);
	}
	return cacheResult;
}
 
Example #26
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
/**
 * Apply any {@link ApplicationContextInitializer}s to the context before it is
 * refreshed.
 * @param context the configured ApplicationContext (not refreshed yet)
 * @see ConfigurableApplicationContext#refresh()
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void applyInitializers(ConfigurableApplicationContext context) {
	for (ApplicationContextInitializer initializer : getInitializers()) {
		Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
				initializer.getClass(), ApplicationContextInitializer.class);
		Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
		initializer.initialize(context);
	}
}
 
Example #27
Source File: FdfsResponse.java    From FastDFS_Client with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 构造函数
 */
@SuppressWarnings("unchecked")
public FdfsResponse() {
    super();
    this.genericType = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), FdfsResponse.class);
    // Type theclass = this.getClass().getGenericSuperclass();
    // this.genericType = ((ParameterizedType)
    // theclass).getActualTypeArguments()[0];
}
 
Example #28
Source File: DependencyDescriptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Optionally set the concrete class that contains this dependency.
 * This may differ from the class that declares the parameter/field in that
 * it may be a subclass thereof, potentially substituting type variables.
 * @since 4.0
 */
public void setContainingClass(Class<?> containingClass) {
	this.containingClass = containingClass;
	this.resolvableType = null;
	if (this.methodParameter != null) {
		GenericTypeResolver.resolveParameterType(this.methodParameter, containingClass);
	}
}
 
Example #29
Source File: AbstractAutowireCapableBeanFactory.java    From java-technology-stack 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);
			}
		}
	});

	return (objectType.value != null && Object.class != objectType.value ? objectType.value : null);
}
 
Example #30
Source File: HandlerMethod.java    From java-technology-stack with MIT License 5 votes vote down vote up
private MethodParameter[] initMethodParameters() {
	int count = this.bridgedMethod.getParameterCount();
	MethodParameter[] result = new MethodParameter[count];
	for (int i = 0; i < count; i++) {
		HandlerMethodParameter parameter = new HandlerMethodParameter(i);
		GenericTypeResolver.resolveParameterType(parameter, this.beanType);
		result[i] = parameter;
	}
	return result;
}