0

I just want to load .jar libraries in my running programm. Therefore i created a "libs" folder in my programm directory.

In the main in call the function loadDependencies() to load all the .jar files in the libs directory to use them in a plugin extension system.

Now the problem, it does not work :)

Here the code i tried so far:

public class DependencyLoader {
    private static final Class<?>[] parameters = new Class[]{URL.class};

    public static void addFile(String s) throws IOException {
        File f = new File(s);
        addFile(f);
    }

    public static void addFile(File f) throws IOException {
        addURL(f.toURI().toURL());
    }

    public static void addURL(URL u) throws IOException {
        URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Class<?> sysclass = URLClassLoader.class;
        try {
            Method method = sysclass.getDeclaredMethod("addURL",parameters);
            method.setAccessible(true);
            method.invoke(sysloader,new Object[]{ u });
        } catch (Throwable t) {
            t.printStackTrace();
            throw new IOException("Error, could not add URL to system classloader");
        }
    }

    public static void loadDependencies(){
        File libsDir = new File("/home/admin/network/lobby/libs");
        if(!libsDir.exists() && !libsDir.mkdirs() && !libsDir.isDirectory()){
            System.out.println("could not find lib directory!");
            System.exit(-1);
        }
        for(File file : libsDir.listFiles()){
            if(file.getName().endsWith(".jar")){
                System.out.println("loading dependency "+file.getName());
                try {
                    addFile(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

The libraries are found . But not loaded correctly. The result is a noclassdef error.

Hope someone can help me.

Regards!

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
Marvin
  • 1
  • There is an ambiguity in the way you pass parameters to the `Method`. try `method.invoke(sysloader, u);` rather. – Maurice Perry Feb 11 '22 at 13:04
  • 1
    This code will not work with Java 9 and later because from Java 9 onwards `ClassLoader.getSystemClassLoader()` will no longer return an `URLClassLoader`. You should better create your own class loader, see for example https://stackoverflow.com/a/45657131/5646962 – Thomas Kläger Feb 11 '22 at 13:24

0 Answers0