How to load JAR files dynamically at Runtime?

前端 未结 20 3236
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 05:15

Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I\'m told there\'s a way of doing it b

20条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 05:49

    The best I've found is org.apache.xbean.classloader.JarFileClassLoader which is part of the XBean project.

    Here's a short method I've used in the past, to create a class loader from all the lib files in a specific directory

    public void initialize(String libDir) throws Exception {
        File dependencyDirectory = new File(libDir);
        File[] files = dependencyDirectory.listFiles();
        ArrayList urls = new ArrayList();
        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().endsWith(".jar")) {
            urls.add(files[i].toURL());
            //urls.add(files[i].toURI().toURL());
            }
        }
        classLoader = new JarFileClassLoader("Scheduler CL" + System.currentTimeMillis(), 
            urls.toArray(new URL[urls.size()]), 
            GFClassLoader.class.getClassLoader());
    }
    

    Then to use the classloader, just do:

    classLoader.loadClass(name);
    

提交回复
热议问题