Java 全局ClassLoader的实现

原创
2020/06/02 13:56
阅读数 388

一、ClassLoader全局范围内生效

public class RuntimeClassLoader {

    private final static Set<String> sClassPaths = new HashSet<>();


    public synchronized void addClassPath(String classPath) {
        sClassPaths.add(classPath);
    }


    private static void loadClassPathClasses(File jarFile) {
        //获取类加载器的addURL方法,准备动态调用
        Method method = null;
        try {
            method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        } catch (NoSuchMethodException | SecurityException e1) {
            e1.printStackTrace();
        }
        // 获取方法的访问权限,保存原始值
        boolean accessible = method.isAccessible();
        try {
            //修改访问权限为可写
            if (accessible == false) {
                method.setAccessible(true);
            }
            // 获取系统类加载器
            URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
            //获取jar文件的url路径
            URL url = jarFile.toURI().toURL();
            //jar路径加入到系统url路径里
            method.invoke(classLoader, url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //回写访问权限
            method.setAccessible(accessible);
        }
    }

   
}

 

注意:classpath设置需要注意以下3点

1、若是jar,那么classpath为jar所在的目录

2、若是class,那么classpath为class文件包名起始目录

3、classpath不推荐使用class文件全路径

 

二、调用和以往方式类似,通过Class.forName

这里要注意,如果要加载一个类,但不希望static标记的代码执行,需要使用

forName(String name, boolean initialize,ClassLoader loader)

第二个参数设置为false

 

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部