Loading libraries at runtime

4

Is there any contraindication in loading libraries .jar at runtime?

I found this code that does this:

URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;

try {
      Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});
      method.setAccessible(true);
      method.invoke(sysloader, new Object[]{URL_CARREGAR});
} catch (Throwable t) {
      t.printStackTrace();
      throw new IOException("Error, could not add URL to system classloader");
}

This code works. But is this the best way?

I want to load at run time so that new JARs can be placed in a folder and so load new functionality into my system. As if they were additional modules.

    
asked by anonymous 28.07.2016 / 19:26

2 answers

2

It is not contraindicated to carry jars at runtime, on the contrary. Developing applications that work that way is desirable. So we can change a part of the software without having to recompile it completely without even stopping it.

Your thinking is correct.

The use of this type of approach can be observed in plugins. Plugins add features to software at runtime. Sometimes it is necessary to restart the software so that it can load the plugin, but the beauty of the solution is not lost.

    
15.08.2016 / 17:28
3

This code is good as it is versatile, simple, useful and flexible. You can leave it a little better like this:

public static void adicionarAoClasspath(String caminho) throws IOException {
   adicionarAoClasspath(new File(caminho).toURI().toURL());
}

public static void adicionarAoClasspath(URL url) throws IOException {
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();

    try {
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        method.setAccessible(true);
        method.invoke(sysloader, url);
    } catch (Throwable t) {
        t.printStackTrace();
        throw new IOException("Error, could not add URL to system classloader", t);
    }
}

The difference is in the concatenation of exceptions, in the use of varargs where possible and in the use of the class literal without needing an intermediate variable for this. In addition, it parameterizes what in its original code was URL_CARREGAR .

    
05.08.2016 / 19:28