下面列出了org.springframework.util.ClassUtils#forName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
private static CacheAwareContextLoaderDelegate createCacheAwareContextLoaderDelegate() {
Class<? extends CacheAwareContextLoaderDelegate> clazz = null;
try {
clazz = (Class<? extends CacheAwareContextLoaderDelegate>) ClassUtils.forName(
DEFAULT_CACHE_AWARE_CONTEXT_LOADER_DELEGATE_CLASS_NAME, BootstrapUtils.class.getClassLoader());
if (logger.isDebugEnabled()) {
logger.debug(String.format("Instantiating CacheAwareContextLoaderDelegate from class [%s]",
clazz.getName()));
}
return instantiateClass(clazz, CacheAwareContextLoaderDelegate.class);
}
catch (Throwable t) {
throw new IllegalStateException("Could not load CacheAwareContextLoaderDelegate [" + clazz + "]", t);
}
}
public WebDelegatingSmartContextLoader() {
if (groovyPresent) {
try {
Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME,
WebDelegatingSmartContextLoader.class.getClassLoader());
this.xmlLoader = (SmartContextLoader) BeanUtils.instantiateClass(loaderClass);
}
catch (Throwable ex) {
throw new IllegalStateException("Failed to enable support for Groovy scripts; "
+ "could not load class: " + GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME, ex);
}
}
else {
this.xmlLoader = new GenericXmlWebContextLoader();
}
this.annotationConfigLoader = new AnnotationConfigWebContextLoader();
}
@Override
protected Class<?> resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {
try {
if (this.classLoader != null) {
// Use the specified ClassLoader to resolve local classes.
return ClassUtils.forName(classDesc.getName(), this.classLoader);
}
else {
// Use the default ClassLoader...
return super.resolveClass(classDesc);
}
}
catch (ClassNotFoundException ex) {
return resolveFallbackIfPossible(classDesc.getName(), ex);
}
}
void registerAdapter(ReactiveAdapterRegistry registry) {
// TODO: remove reflection when build requires JDK 9+
try {
String publisherName = "java.util.concurrent.Flow.Publisher";
Class<?> publisherClass = ClassUtils.forName(publisherName, getClass().getClassLoader());
String adapterName = "reactor.adapter.JdkFlowAdapter";
Class<?> flowAdapterClass = ClassUtils.forName(adapterName, getClass().getClassLoader());
Method toFluxMethod = flowAdapterClass.getMethod("flowPublisherToFlux", publisherClass);
Method toFlowMethod = flowAdapterClass.getMethod("publisherToFlowPublisher", Publisher.class);
Object emptyFlow = ReflectionUtils.invokeMethod(toFlowMethod, null, Flux.empty());
registry.registerReactiveType(
ReactiveTypeDescriptor.multiValue(publisherClass, () -> emptyFlow),
source -> (Publisher<?>) ReflectionUtils.invokeMethod(toFluxMethod, null, source),
publisher -> ReflectionUtils.invokeMethod(toFlowMethod, null, publisher)
);
}
catch (Throwable ex) {
// Ignore
}
}
static Collection<BinderType> parseBinderConfigurations(ClassLoader classLoader,
Resource resource) throws IOException, ClassNotFoundException {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
Collection<BinderType> parsedBinderConfigurations = new ArrayList<>();
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String binderType = (String) entry.getKey();
String[] binderConfigurationClassNames = StringUtils
.commaDelimitedListToStringArray((String) entry.getValue());
Class<?>[] binderConfigurationClasses = new Class[binderConfigurationClassNames.length];
int i = 0;
for (String binderConfigurationClassName : binderConfigurationClassNames) {
binderConfigurationClasses[i++] = ClassUtils
.forName(binderConfigurationClassName, classLoader);
}
parsedBinderConfigurations
.add(new BinderType(binderType, binderConfigurationClasses));
}
return parsedBinderConfigurations;
}
private SourceClass getRelated(String className) throws IOException {
if (this.source instanceof Class) {
try {
Class<?> clazz = ClassUtils.forName(className, ((Class<?>) this.source).getClassLoader());
return asSourceClass(clazz);
}
catch (ClassNotFoundException ex) {
// Ignore -> fall back to ASM next, except for core java types.
if (className.startsWith("java")) {
throw new NestedIOException("Failed to load class [" + className + "]", ex);
}
return new SourceClass(metadataReaderFactory.getMetadataReader(className));
}
}
return asSourceClass(className);
}
/**
* Get the singleton {@code H2EmbeddedDatabaseConfigurer} instance.
* @return the configurer instance
* @throws ClassNotFoundException if H2 is not on the classpath
*/
@SuppressWarnings("unchecked")
public static synchronized H2EmbeddedDatabaseConfigurer getInstance() throws ClassNotFoundException {
if (instance == null) {
instance = new H2EmbeddedDatabaseConfigurer( (Class<? extends Driver>)
ClassUtils.forName("org.h2.Driver", H2EmbeddedDatabaseConfigurer.class.getClassLoader()));
}
return instance;
}
/**
* Get the java Object type for the MimeType X_JAVA_OBJECT.
* @param contentType content type
* @return the class for the content type.
*/
public static Class<?> getJavaTypeForJavaObjectContentType(MimeType contentType) {
Assert.isTrue(X_JAVA_OBJECT.includes(contentType), "Content type must be "
+ X_JAVA_OBJECT.toString() + ", or " + "included in it");
if (contentType.getParameter("type") != null) {
try {
return ClassUtils.forName(contentType.getParameter("type"), null);
}
catch (Exception e) {
throw new ConversionException(e.getMessage(), e);
}
}
return Object.class;
}
@Test
public void embeddedCandidatesAreDetected()
throws IOException, ClassNotFoundException {
// Validate nested type structure
String nestedType = "org.springframework.context.index.sample.SampleEmbedded.Another$AnotherPublicCandidate";
Class<?> type = ClassUtils.forName(nestedType, getClass().getClassLoader());
assertThat(type, sameInstance(SampleEmbedded.Another.AnotherPublicCandidate.class));
CandidateComponentsMetadata metadata = compile(SampleEmbedded.class);
assertThat(metadata, hasComponent(
SampleEmbedded.PublicCandidate.class, Component.class));
assertThat(metadata, hasComponent(nestedType, Component.class.getName()));
assertThat(metadata.getItems(), hasSize(2));
}
/**
* Create a List of default strategy objects for the given strategy interface.
* <p>The default implementation uses the "DispatcherServlet.properties" file (in the same
* package as the DispatcherServlet class) to determine the class names. It instantiates
* the strategy objects through the context's BeanFactory.
* @param context the current WebApplicationContext
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
*/
@SuppressWarnings("unchecked")
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
String key = strategyInterface.getName();
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
List<T> strategies = new ArrayList<T>(classNames.length);
for (String className : classNames) {
try {
Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
Object strategy = createDefaultStrategy(context, clazz);
strategies.add((T) strategy);
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]", ex);
}
catch (LinkageError err) {
throw new BeanInitializationException(
"Error loading DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]: problem with class file or dependent class", err);
}
}
return strategies;
}
else {
return new LinkedList<T>();
}
}
/**
* Create a List of default strategy objects for the given strategy interface.
* <p>The default implementation uses the "DispatcherServlet.properties" file (in the same
* package as the DispatcherServlet class) to determine the class names. It instantiates
* the strategy objects through the context's BeanFactory.
* @param context the current WebApplicationContext
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
*/
@SuppressWarnings("unchecked")
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
// 策略接口名称
String key = strategyInterface.getName();
// 默认策略列表
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
List<T> strategies = new ArrayList<>(classNames.length);
for (String className : classNames) {
try {
// 实例化
Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
Object strategy = createDefaultStrategy(context, clazz);
strategies.add((T) strategy);
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]", ex);
}
catch (LinkageError err) {
throw new BeanInitializationException(
"Unresolvable class definition for DispatcherServlet's default strategy class [" +
className + "] for interface [" + key + "]", err);
}
}
return strategies;
}
else {
return new LinkedList<>();
}
}
/**
* Get the singleton {@link HsqlEmbeddedDatabaseConfigurer} instance.
* @return the configurer
* @throws ClassNotFoundException if HSQL is not on the classpath
*/
@SuppressWarnings("unchecked")
public static synchronized HsqlEmbeddedDatabaseConfigurer getInstance() throws ClassNotFoundException {
if (instance == null) {
instance = new HsqlEmbeddedDatabaseConfigurer( (Class<? extends Driver>)
ClassUtils.forName("org.hsqldb.jdbcDriver", HsqlEmbeddedDatabaseConfigurer.class.getClassLoader()));
}
return instance;
}
private static Class<?> getStartClass(List<URL> list, ClassLoader classLoader) {
logger.info("Searching manifests: " + list);
for (URL url : list) {
try {
InputStream inputStream = null;
Manifest manifest = new Manifest(url.openStream());
logger.info("Searching for start class in manifest: " + url);
if (logger.isDebugEnabled()) {
manifest.write(System.out);
}
try {
String startClassName = manifest.getMainAttributes().getValue("Start-Class");
if (!StringUtils.hasText(startClassName)) {
startClassName = manifest.getMainAttributes().getValue("Main-Class");
}
if (StringUtils.hasText(startClassName)) {
Class<?> startClass = ClassUtils.forName(startClassName, classLoader);
if (isSpringBootApplication(startClass)) {
logger.info("Loaded Start Class: " + startClass);
return startClass;
}
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
catch (Exception ex) {
logger.debug("Failed to determine Start-Class in manifest file of " + url, ex);
}
}
return null;
}
/**
* Parse a method signature in the form {@code methodName[([arg_list])]},
* where {@code arg_list} is an optional, comma-separated list of fully-qualified
* type names, and attempts to resolve that signature against the supplied {@code Class}.
* <p>When not supplying an argument list ({@code methodName}) the method whose name
* matches and has the least number of parameters will be returned. When supplying an
* argument type list, only the method whose name and argument types match will be returned.
* <p>Note then that {@code methodName} and {@code methodName()} are <strong>not</strong>
* resolved in the same way. The signature {@code methodName} means the method called
* {@code methodName} with the least number of arguments, whereas {@code methodName()}
* means the method called {@code methodName} with exactly 0 arguments.
* <p>If no method can be found, then {@code null} is returned.
* @param signature the method signature as String representation
* @param clazz the class to resolve the method signature against
* @return the resolved Method
* @see #findMethod
* @see #findMethodWithMinimalParameters
*/
public static Method resolveSignature(String signature, Class<?> clazz) {
Assert.hasText(signature, "'signature' must not be empty");
Assert.notNull(clazz, "Class must not be null");
int firstParen = signature.indexOf("(");
int lastParen = signature.indexOf(")");
if (firstParen > -1 && lastParen == -1) {
throw new IllegalArgumentException("Invalid method signature '" + signature +
"': expected closing ')' for args list");
}
else if (lastParen > -1 && firstParen == -1) {
throw new IllegalArgumentException("Invalid method signature '" + signature +
"': expected opening '(' for args list");
}
else if (firstParen == -1 && lastParen == -1) {
return findMethodWithMinimalParameters(clazz, signature);
}
else {
String methodName = signature.substring(0, firstParen);
String[] parameterTypeNames =
StringUtils.commaDelimitedListToStringArray(signature.substring(firstParen + 1, lastParen));
Class<?>[] parameterTypes = new Class<?>[parameterTypeNames.length];
for (int i = 0; i < parameterTypeNames.length; i++) {
String parameterTypeName = parameterTypeNames[i].trim();
try {
parameterTypes[i] = ClassUtils.forName(parameterTypeName, clazz.getClassLoader());
}
catch (Throwable ex) {
throw new IllegalArgumentException("Invalid method signature: unable to resolve type [" +
parameterTypeName + "] for argument " + i + ". Root cause: " + ex);
}
}
return findMethod(clazz, methodName, parameterTypes);
}
}
protected static Collection<ResolvedMigration> resolveMigrations(Flyway flyway, String... locations) throws ClassNotFoundException {
MigrationResolver resolver = createMigrationResolver(flyway, locations);
if (flywayVersion >= 52) {
Object configInstance = getField(flyway, "configuration");
Class<?> contextType = ClassUtils.forName("org.flywaydb.core.api.resolver.Context", classLoader);
Object contextInstance = ProxyFactory.getProxy(contextType, (MethodInterceptor) invocation ->
"getConfiguration".equals(invocation.getMethod().getName()) ? configInstance : invocation.proceed());
return invokeMethod(resolver, "resolveMigrations", contextInstance);
} else {
return resolver.resolveMigrations();
}
}
/**
* Locate the {@link NamespaceHandler} for the supplied namespace URI
* from the configured mappings.
* @param namespaceUri the relevant namespace URI
* @return the located {@link NamespaceHandler}, or {@code null} if none found
*/
@Override
@Nullable
public NamespaceHandler resolve(String namespaceUri) {
Map<String, Object> handlerMappings = getHandlerMappings();
Object handlerOrClassName = handlerMappings.get(namespaceUri);
if (handlerOrClassName == null) {
return null;
}
else if (handlerOrClassName instanceof NamespaceHandler) {
return (NamespaceHandler) handlerOrClassName;
}
else {
String className = (String) handlerOrClassName;
try {
Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {
throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri +
"] does not implement the [" + NamespaceHandler.class.getName() + "] interface");
}
NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
namespaceHandler.init();
handlerMappings.put(namespaceUri, namespaceHandler);
return namespaceHandler;
}
catch (ClassNotFoundException ex) {
throw new FatalBeanException("Could not find NamespaceHandler class [" + className +
"] for namespace [" + namespaceUri + "]", ex);
}
catch (LinkageError err) {
throw new FatalBeanException("Unresolvable class definition for NamespaceHandler class [" +
className + "] for namespace [" + namespaceUri + "]", err);
}
}
}
public FailingBeforeAndAfterMethodsTestNGTests(String testClassName, int expectedTestStartCount,
int expectedTestSuccessCount, int expectedFailureCount, int expectedFailedConfigurationsCount) throws Exception {
this.clazz = ClassUtils.forName(getClass().getName() + "." + testClassName, getClass().getClassLoader());
this.expectedTestStartCount = expectedTestStartCount;
this.expectedTestSuccessCount = expectedTestSuccessCount;
this.expectedFailureCount = expectedFailureCount;
this.expectedFailedConfigurationsCount = expectedFailedConfigurationsCount;
}
public FailingBeforeAndAfterMethodsJUnitTests(String testClassName) throws Exception {
this.clazz = ClassUtils.forName(getClass().getName() + "." + testClassName, getClass().getClassLoader());
}
@Override
protected Class<?> resolveClassName(String className) throws ClassNotFoundException {
return ClassUtils.forName(className, this.beanClassLoader);
}
@Override
protected Class<?> resolveClassName(String className) throws ClassNotFoundException {
return ClassUtils.forName(className, this.beanClassLoader);
}