A função do método Class.forName
1. Carregue a classe dada na memória
2. Inicialize a classe dada
Então a JVM pode usá-lo
Por exemplo
O código-fonte vem do pagehelper do projeto de código aberto
/**
* 创建 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);
}
}
}