何白白

我的java开发记录


Project maintained by hjx601496320 Hosted on GitHub Pages — Theme by mattgraham

动态加载class,卸载class

从指定位置的jar中加载class,和卸载class

第一种
        URL url = new File("/文件路径/entityMaker.jar").toURI().toURL();
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        URLClassLoader classLoader = new URLClassLoader(
                new URL[]{url},
                systemClassLoader
        );

        //加载class

        //不能使用Class.forName("com.hebaibai.entitymaker.util.SqlUtils")加载Class
        Class sqlUtils = classLoader.loadClass("com.hebaibai.entitymaker.util.SqlUtils");
        final Object instance = sqlUtils.newInstance();
        System.out.println(instance.getClass());

        //卸载类
        Method close = URLClassLoader.class.getDeclaredMethod("close");
        close.invoke(classLoader);
        
        //已经加载过得没法卸载
        sqlUtils = classLoader.loadClass("com.hebaibai.entitymaker.util.FileUtils");
        instance = sqlUtils.newInstance();
        System.out.println(instance.getClass());
第二种
        URL url = new File("/home/hjx/Desktop/entityMaker/entityMaker.jar").toURI().toURL();
        URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        if (!addURL.isAccessible()) {
            addURL.setAccessible(true);
        }
        addURL.invoke(classLoader, url);
        addURL.setAccessible(addURL.isAccessible());
        //可以使用Class.forName("com.hebaibai.entitymaker.util.SqlUtils")加载Class
        Class<?> aClass = Class.forName("com.hebaibai.entitymaker.util.SqlUtils");
        Object instance = aClass.newInstance();
        System.out.println(instance.getClass());