Java Code Examples for org.springframework.core.GenericTypeResolver#resolveTypeArgument()

The following examples show how to use org.springframework.core.GenericTypeResolver#resolveTypeArgument() . 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 spring4-understanding with Apache License 2.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) {
			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 " +
					"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: 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 3
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 4
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 5
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 6
Source File: ContextLoader.java    From java-technology-stack 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 7
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 8
Source File: FormattingConversionService.java    From spring-analysis-note with MIT License 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 9
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 10
Source File: AbstractContextLoader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void invokeApplicationContextInitializers(ConfigurableApplicationContext context,
		MergedContextConfiguration mergedConfig) {

	Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses =
			mergedConfig.getContextInitializerClasses();
	if (initializerClasses.isEmpty()) {
		// no ApplicationContextInitializers have been declared -> nothing to do
		return;
	}

	List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<>();
	Class<?> contextClass = context.getClass();

	for (Class<? extends ApplicationContextInitializer<?>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(context)) {
			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(),
					contextClass.getName()));
		}
		initializerInstances.add((ApplicationContextInitializer<ConfigurableApplicationContext>) BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(initializerInstances);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
		initializer.initialize(context);
	}
}
 
Example 11
Source File: FormattingConversionService.java    From java-technology-stack with MIT License 5 votes vote down vote up
static Class<?> getFieldType(Formatter<?> formatter) {
	Class<?> fieldType = GenericTypeResolver.resolveTypeArgument(formatter.getClass(), Formatter.class);
	if (fieldType == null && formatter instanceof DecoratingProxy) {
		fieldType = GenericTypeResolver.resolveTypeArgument(
				((DecoratingProxy) formatter).getDecoratedClass(), Formatter.class);
	}
	if (fieldType == null) {
		throw new IllegalArgumentException("Unable to extract the parameterized field type from Formatter [" +
				formatter.getClass().getName() + "]; does the class parameterize the <T> generic type?");
	}
	return fieldType;
}
 
Example 12
Source File: AbstractContextLoader.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void invokeApplicationContextInitializers(ConfigurableApplicationContext context,
		MergedContextConfiguration mergedConfig) {
	Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = mergedConfig.getContextInitializerClasses();
	if (initializerClasses.isEmpty()) {
		// no ApplicationContextInitializers have been declared -> nothing to do
		return;
	}

	List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();
	Class<?> contextClass = context.getClass();

	for (Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
			ApplicationContextInitializer.class);
		Assert.isAssignable(initializerContextClass, contextClass, 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 "
					+ "context loader [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
			contextClass.getName()));
		initializerInstances.add((ApplicationContextInitializer<ConfigurableApplicationContext>) BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(initializerInstances);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
		initializer.initialize(context);
	}
}
 
Example 13
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 14
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 15
Source File: EventBusListenerWrapper.java    From vaadin4spring with Apache License 2.0 4 votes vote down vote up
EventBusListenerWrapper(EventBus owningEventBus, EventBusListener<?> listenerTarget, String topic, boolean includingPropagatingEvents) {
    super(owningEventBus, listenerTarget, topic, includingPropagatingEvents);
    payloadType = GenericTypeResolver.resolveTypeArgument(listenerTarget.getClass(), EventBusListener.class);
    Assert.notNull(payloadType, "Could not resolve payload type");
}
 
Example 16
Source File: AbstractDynamoDBEventListener.java    From spring-data-dynamodb with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new {@link AbstractDynamoDBEventListener}.
 */
public AbstractDynamoDBEventListener() {
	Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(
			this.getClass(), AbstractDynamoDBEventListener.class);
	this.domainClass = typeArgument == null ? Object.class : typeArgument;
}
 
Example 17
Source File: PluginChannelRegistry.java    From Cleanstone with MIT License 4 votes vote down vote up
private <T extends PluginChannel.PluginMessage> boolean messageTypeMatches(T pluginMessage, PluginChannel<?> pluginChannel) {
    Class<?> messageClass = GenericTypeResolver.resolveTypeArgument(pluginChannel.getClass(), PluginChannel.class);

    return pluginMessage.getClass().equals(messageClass);
}
 
Example 18
Source File: VersionAction.java    From Brutusin-RPC with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    Class<?> resolveTypeArgument = GenericTypeResolver.resolveTypeArgument(VersionAction.class, RpcAction.class);
    System.out.println(resolveTypeArgument);
}
 
Example 19
Source File: SpringFactoryImportSelector.java    From spring-cloud-commons with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected SpringFactoryImportSelector() {
	this.annotationClass = (Class<T>) GenericTypeResolver
			.resolveTypeArgument(this.getClass(), SpringFactoryImportSelector.class);
}
 
Example 20
Source File: FormattingConversionService.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Nullable
private Class<?> resolvePrinterObjectType(Printer<?> printer) {
	return GenericTypeResolver.resolveTypeArgument(printer.getClass(), Printer.class);
}