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

The following examples show how to use org.springframework.util.ClassUtils#resolveClassName() . 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: ShutdownApplicationListener.java    From spring-boot-graal-feature with Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> sources(ApplicationReadyEvent event) {
    Method method = ReflectionUtils.findMethod(SpringApplication.class,
            "getAllSources");
    if (method == null) {
        method = ReflectionUtils.findMethod(SpringApplication.class, "getSources");
    }
    ReflectionUtils.makeAccessible(method);
    @SuppressWarnings("unchecked")
    Set<Object> objects = (Set<Object>) ReflectionUtils.invokeMethod(method,
            event.getSpringApplication());
    Set<Class<?>> result = new LinkedHashSet<>();
    for (Object object : objects) {
        if (object instanceof String) {
            object = ClassUtils.resolveClassName((String) object, null);
        }
        result.add((Class<?>) object);
    }
    return result;
}
 
Example 2
Source File: AnnotationDrivenBeanDefinitionParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) {
	ManagedList<Object> result = new ManagedList<Object>();
	for (Object object : list) {
		if (object instanceof BeanDefinitionHolder) {
			BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object;
			String className = beanDef.getBeanDefinition().getBeanClassName();
			Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader());
			if (WebArgumentResolver.class.isAssignableFrom(clazz)) {
				RootBeanDefinition adapter = new RootBeanDefinition(ServletWebArgumentResolverAdapter.class);
				adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef);
				result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter"));
				continue;
			}
		}
		result.add(object);
	}
	return result;
}
 
Example 3
Source File: FunctionConfiguration.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
private PollableBean extractPollableAnnotation(StreamFunctionProperties functionProperties, GenericApplicationContext context,
		BindableFunctionProxyFactory proxyFactory) {
	// here we need to ensure that for cases where composition is defined we only look for supplier method to find Pollable annotation.
	String supplierFunctionName = StringUtils
			.delimitedListToStringArray(proxyFactory.getFunctionDefinition().replaceAll(",", "|").trim(), "|")[0];
	BeanDefinition bd = context.getBeanDefinition(supplierFunctionName);
	if (!(bd instanceof RootBeanDefinition)) {
		return null;
	}

	Method factoryMethod = ((RootBeanDefinition) bd).getResolvedFactoryMethod();
	if (factoryMethod == null) {
		Object source = bd.getSource();
		if (source instanceof MethodMetadata) {
			Class<?> factory = ClassUtils.resolveClassName(((MethodMetadata) source).getDeclaringClassName(), null);
			Class<?>[] params = FunctionContextUtils.getParamTypesFromBeanDefinitionFactory(factory, (RootBeanDefinition) bd);
			factoryMethod = ReflectionUtils.findMethod(factory, ((MethodMetadata) source).getMethodName(), params);
		}
	}
	Assert.notNull(factoryMethod, "Failed to introspect factory method since it was not discovered for function '"
			+ functionProperties.getDefinition() + "'");
	return factoryMethod.getReturnType().isAssignableFrom(Supplier.class)
			? AnnotationUtils.findAnnotation(factoryMethod, PollableBean.class)
					: null;
}
 
Example 4
Source File: AnnotationDrivenBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
private ManagedList<Object> wrapLegacyResolvers(List<Object> list, ParserContext context) {
	ManagedList<Object> result = new ManagedList<>();
	for (Object object : list) {
		if (object instanceof BeanDefinitionHolder) {
			BeanDefinitionHolder beanDef = (BeanDefinitionHolder) object;
			String className = beanDef.getBeanDefinition().getBeanClassName();
			Assert.notNull(className, "No resolver class");
			Class<?> clazz = ClassUtils.resolveClassName(className, context.getReaderContext().getBeanClassLoader());
			if (WebArgumentResolver.class.isAssignableFrom(clazz)) {
				RootBeanDefinition adapter = new RootBeanDefinition(ServletWebArgumentResolverAdapter.class);
				adapter.getConstructorArgumentValues().addIndexedArgumentValue(0, beanDef);
				result.add(new BeanDefinitionHolder(adapter, beanDef.getBeanName() + "Adapter"));
				continue;
			}
		}
		result.add(object);
	}
	return result;
}
 
Example 5
Source File: LocalVariableTableParameterNameDiscoverer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private Member resolveMember() {
	ClassLoader loader = this.clazz.getClassLoader();
	Class<?>[] argTypes = new Class<?>[this.args.length];
	for (int i = 0; i < this.args.length; i++) {
		argTypes[i] = ClassUtils.resolveClassName(this.args[i].getClassName(), loader);
	}
	try {
		if (CONSTRUCTOR.equals(this.name)) {
			return this.clazz.getDeclaredConstructor(argTypes);
		}
		return this.clazz.getDeclaredMethod(this.name, argTypes);
	}
	catch (NoSuchMethodException ex) {
		throw new IllegalStateException("Method [" + this.name +
				"] was discovered in the .class file but cannot be resolved in the class object", ex);
	}
}
 
Example 6
Source File: FunctionalInstallerImportRegistrars.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private Class<?> resolve(ClassLoader classLoader, String typeName) {
	if (ClassUtils.isPresent(typeName, classLoader)) {
		Class<?> clazz = ClassUtils.resolveClassName(typeName, classLoader);
		return clazz;
	}
	return null;
}
 
Example 7
Source File: InterfaceBasedMBeanInfoAssembler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve the given class names into Class objects.
 * @param classNames the class names to resolve
 * @param beanKey the bean key that the class names are associated with
 * @return the resolved Class
 */
private Class<?>[] resolveClassNames(String[] classNames, String beanKey) {
	Class<?>[] classes = new Class<?>[classNames.length];
	for (int x = 0; x < classes.length; x++) {
		Class<?> cls = ClassUtils.resolveClassName(classNames[x].trim(), this.beanClassLoader);
		if (!cls.isInterface()) {
			throw new IllegalArgumentException(
					"Class [" + classNames[x] + "] mapped to bean key [" + beanKey + "] is no interface");
		}
		classes[x] = cls;
	}
	return classes;
}
 
Example 8
Source File: RefreshEndpointTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private int countShutdownHooks() {
	Class<?> type = ClassUtils.resolveClassName("java.lang.ApplicationShutdownHooks",
			null);
	Field field = ReflectionUtils.findField(type, "hooks");
	ReflectionUtils.makeAccessible(field);
	@SuppressWarnings("rawtypes")
	Map map = (Map) ReflectionUtils.getField(field, null);
	return map.size();
}
 
Example 9
Source File: EnumValueHintProvider.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Override
public List<ValueHint> generateValueHints(ConfigurationMetadataProperty property, ClassLoader classLoader) {
	List<ValueHint> result = new ArrayList<>();
	if (ClassUtils.isPresent(property.getType(), classLoader)) {
		Class<?> clazz = ClassUtils.resolveClassName(property.getType(), classLoader);
		if (clazz.isEnum()) {
			for (Object o : clazz.getEnumConstants()) {
				ValueHint hint = new ValueHint();
				hint.setValue(o);
				result.add(hint);
			}
		}
	}
	return result;
}
 
Example 10
Source File: FunctionClassUtils.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
static Class<?> getStartClass(ClassLoader classLoader) {
	Class<?> mainClass = null;
	if (System.getenv("MAIN_CLASS") != null) {
		mainClass = ClassUtils.resolveClassName(System.getenv("MAIN_CLASS"), classLoader);
	}
	else if (System.getProperty("MAIN_CLASS") != null) {
		mainClass = ClassUtils.resolveClassName(System.getProperty("MAIN_CLASS"), classLoader);
	}
	else {
		try {
			Class<?> result = getStartClass(
					Collections.list(classLoader.getResources(JarFile.MANIFEST_NAME)), classLoader);
			if (result == null) {
				result = getStartClass(Collections
						.list(classLoader.getResources("meta-inf/manifest.mf")), classLoader);
			}
			Assert.notNull(result, "Failed to locate main class");
			mainClass = result;
		}
		catch (Exception ex) {
			throw new IllegalStateException("Failed to discover main class. An attempt was made to discover "
					+ "main class as 'MAIN_CLASS' environment variable, system property as well as "
					+ "entry in META-INF/MANIFEST.MF (in that order).", ex);
		}
	}
	logger.info("Main class: " + mainClass);
	return mainClass;
}
 
Example 11
Source File: ClassArrayEditor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setAsText(String text) throws IllegalArgumentException {
	if (StringUtils.hasText(text)) {
		String[] classNames = StringUtils.commaDelimitedListToStringArray(text);
		Class<?>[] classes = new Class<?>[classNames.length];
		for (int i = 0; i < classNames.length; i++) {
			String className = classNames[i].trim();
			classes[i] = ClassUtils.resolveClassName(className, this.classLoader);
		}
		setValue(classes);
	}
	else {
		setValue(null);
	}
}
 
Example 12
Source File: CustomAutowireConfigurer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (this.customQualifierTypes != null) {
		if (!(beanFactory instanceof DefaultListableBeanFactory)) {
			throw new IllegalStateException(
					"CustomAutowireConfigurer needs to operate on a DefaultListableBeanFactory");
		}
		DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory;
		if (!(dlbf.getAutowireCandidateResolver() instanceof QualifierAnnotationAutowireCandidateResolver)) {
			dlbf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
		}
		QualifierAnnotationAutowireCandidateResolver resolver =
				(QualifierAnnotationAutowireCandidateResolver) dlbf.getAutowireCandidateResolver();
		for (Object value : this.customQualifierTypes) {
			Class<? extends Annotation> customType = null;
			if (value instanceof Class) {
				customType = (Class<? extends Annotation>) value;
			}
			else if (value instanceof String) {
				String className = (String) value;
				customType = (Class<? extends Annotation>) ClassUtils.resolveClassName(className, this.beanClassLoader);
			}
			else {
				throw new IllegalArgumentException(
						"Invalid value [" + value + "] for custom qualifier type: needs to be Class or String.");
			}
			if (!Annotation.class.isAssignableFrom(customType)) {
				throw new IllegalArgumentException(
						"Qualifier type [" + customType.getName() + "] needs to be annotation type");
			}
			resolver.addQualifierType(customType);
		}
	}
}
 
Example 13
Source File: EnumValueHintProvider.java    From spring-cloud-dashboard with Apache License 2.0 5 votes vote down vote up
@Override
public List<ValueHint> generateValueHints(ConfigurationMetadataProperty property, ClassLoader classLoader) {
	List<ValueHint> result = new ArrayList<>();
	if (ClassUtils.isPresent(property.getType(), classLoader)) {
		Class<?> clazz = ClassUtils.resolveClassName(property.getType(), classLoader);
		if (clazz.isEnum()) {
			for (Object o : clazz.getEnumConstants()) {
				ValueHint hint = new ValueHint();
				hint.setValue(o);
				result.add(hint);
			}
		}
	}
	return result;
}
 
Example 14
Source File: ConditionEvaluator.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private Condition getCondition(String conditionClassName, ClassLoader classloader) {
	Class<?> conditionClass = ClassUtils.resolveClassName(conditionClassName, classloader);
	return (Condition) BeanUtils.instantiateClass(conditionClass);
}
 
Example 15
Source File: HttpMessageConverterResolver.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
private Class<?> resolveReturnValueClass(RestMethodMetadata restMethodMetadata) {
	String returnClassName = restMethodMetadata.getMethod().getReturnType();
	return ClassUtils.resolveClassName(returnClassName, classLoader);
}
 
Example 16
Source File: Target_MessageInterpolatorFactory.java    From spring-graalvm-native with Apache License 2.0 4 votes vote down vote up
@Substitute
public MessageInterpolator getObject() throws BeansException {
	Class<?> interpolatorClass = ClassUtils.resolveClassName("org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator", null);
	Object interpolator = BeanUtils.instantiateClass(interpolatorClass);
	return (MessageInterpolator) interpolator;
}
 
Example 17
Source File: DataTypeMismatchHighlightingTask.java    From nb-springboot with Apache License 2.0 4 votes vote down vote up
private boolean checkType(String type, String text, ClassLoader cl) throws IllegalArgumentException {
    Class<?> clazz = ClassUtils.resolveClassName(type, cl);
    if (clazz != null) {
        try {
            parser.parseType(text, clazz);
        } catch (Exception e1) {
            if (clazz.isEnum()) {
                // generate and try relaxed variants of value
                for (String relaxedName : new RelaxedNames(text)) {
                    try {
                        parser.parseType(relaxedName, clazz);
                        return true;
                    } catch (Exception e2) {
                        // try another variant
                    }
                    if (canceled) {
                        break;
                    }
                }
                return false;
            } else {
                try {
                    // handle a few specific cases where no direct constructor from string or converter exist
                    switch (type) {
                        case "java.nio.file.Path":
                            Paths.get(text);
                            return true;
                        case "java.util.Locale":
                            LocaleUtils.toLocale(text);
                            return true;
                        case "java.time.Duration":
                            DurationStyle.detectAndParse(text);
                            return true;
                        case "org.springframework.util.unit.DataSize":
                            DataSize.parse(text);
                            return true;
                        case "java.lang.Class":
                            cl.loadClass(text);
                            return true;
                        default:
                            return false;
                    }
                } catch (Exception e3) {
                    return false;
                }
            }
        }
    }
    // unresolvable/unknown class, assume user knows what is doing
    return true;
}
 
Example 18
Source File: MergedAnnotationReadingVisitor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <E extends Enum<E>> void visitEnum(String descriptor, String value, Consumer<E> consumer) {
	String className = Type.getType(descriptor).getClassName();
	Class<E> type = (Class<E>) ClassUtils.resolveClassName(className, this.classLoader);
	consumer.accept(Enum.valueOf(type, value));
}
 
Example 19
Source File: DubboInvocationHandler.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
private Class<?> getReturnType(RestMethodMetadata dubboRestMethodMetadata) {
	String returnType = dubboRestMethodMetadata.getReturnType();
	return ClassUtils.resolveClassName(returnType, classLoader);
}
 
Example 20
Source File: Target_org_springframework_boot_validation_MessageInterpolatorFactory.java    From spring-boot-graal-feature with Apache License 2.0 4 votes vote down vote up
@Substitute
public MessageInterpolator getObject() throws BeansException {
	Class<?> interpolatorClass = ClassUtils.resolveClassName("org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator", null);
	Object interpolator = BeanUtils.instantiateClass(interpolatorClass);
	return (MessageInterpolator) interpolator;
}