How to load all the jars from a directory dynamically?

为君一笑 提交于 2019-12-06 14:29:25

You need to load your jar first and then load the required class from there.

URL myJarFile = new URL("jar","","file:"+jarPath);
URLClassLoader child = new URLClassLoader (myJarFile , this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod ("myMethod");
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance);

Then you can get a list of all the classes in the jar file first:

List<String> classNames=new ArrayList<String>();
ZipInputStream zip=new ZipInputStream(new FileInputStream("/path/to/jar/file.jar"));
for(ZipEntry entry=zip.getNextEntry();entry!=null;entry=zip.getNextEntry())
    if(entry.getName().endsWith(".class") && !entry.isDirectory()) {
        StringBuilder className=new StringBuilder();
        for(String part : entry.getName().split("/")) {
            if(className.length() != 0)
                className.append(".");
            className.append(part);
            if(part.endsWith(".class"))
                className.setLength(className.length()-".class".length());
        }
        classNames.add(className.toString());
    }

Once you have list of your classes do the following:

File file = new File("Absolute Path to your jar");  
            URL url = file.toURI().toURL();  
            URL[] urls = {url};  
            ClassLoader loader = new URLClassLoader(urls);  
            Class myClass = loader.loadClass(classNames.get(0));  
            System.out.println("Executing...");  
            Object tester = myClass.newInstance(); 
        System.out.println("Test");

Apache Felix File Install may be exactly what you want. It will monitor a nominated directory and dynamically load any bundles in it. Only packages exported by the bundles will be available to other bundles on the classpath, but all classes will be loaded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!