Class.forName方法的作用
1、加载给定的类到内存中
2、初始化给定的类
然后 JVM 就可以使用它了
举例
源码来自开源项目 pagehelper
/**
* 创建 SQL 缓存
*
* @param sqlCacheClass
* @return
*/
public static <K, V> Cache<K, V> createCache(String sqlCacheClass, String prefix, Properties properties) {
if (StringUtil.isEmpty(sqlCacheClass)) {
try {
Class.forName("com.google.common.cache.Cache");
// com.google.common.cache.Cache 加载并初始化后,GuavaCache 类的
// CACHE 成员变量就可以直接使用了
return new GuavaCache<K, V>(properties, prefix);
} catch (Throwable t) {
return new SimpleCache<K, V>(properties, prefix);
}
} else {
try {
Class<? extends Cache> clazz = (Class<? extends Cache>) Class.forName(sqlCacheClass);
try {
Constructor<? extends Cache> constructor = clazz.getConstructor(Properties.class, String.class);
return constructor.newInstance(properties, prefix);
} catch (Exception e) {
return clazz.newInstance();
}
} catch (Throwable t) {
throw new PageException("Created Sql Cache [" + sqlCacheClass + "] Error", t);
}
}
}