Class.forName 使用

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);
        }
    }
}

相关文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值