简体   繁体   中英

Dynamically load a JAR using URLClassLoader?

I have a program which needs to be able to dynamically load JARs at runtime - after looking around I beleive this uses URLClassLoader, but I'm not sure how to get it to work. The JAR "openup.jar" is in the same directory as the program.

Ideally I would like to be able to load this JAR without having to specify each individual class inside it.

What I successfully used:

@SuppressWarnings("unchecked")
public void addURL(URL u) throws IOException {
    URLClassLoader sysLoader = (URLClassLoader) ThisClass.class.getClassLoader();
    URL urls[] = sysLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (urls[i].toString().equalsIgnoreCase(u.toString())) {
            return;
        }
    }
    Class sysclass = URLClassLoader.class;
    try {
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { u });
    } catch (Throwable t) {
        throw new IOException("Error, could not add URL to system classloader");
    }
}

An almost identical solution is indeed presented in How should I load Jars dynamically at runtime?

Here I am explaining the full process of creating a jar and then loading a jar dynamically in another project:

Steps to create jar:

  1. Create a new Project in any IDE(Eclipse).
  2. Add a Sample class in packages(in my case MyClass).
  3. Do right-click on the project and then export as jar and give a local path of system location where the jar wants to keep(right-click -> Export -> choose java/jar file -> next ->give path -> finish).
  4. Then jar will be available at given location.

package newJar.com.example;

public class MyClass {

public MyClass() {
    // TODO Auto-generated constructor stub
}

public void helloWorld() {
    System.out.println("Hello from the helloWorld");
}

}

Steps to load the jar dynamically:

  1. Create a new project and add below code:

    public class CustomClass {

    public CustomClass() { // TODO Auto-generated constructor stub }

    public void getCall(File myJar) {

     try { URLClassLoader loader = new URLClassLoader(new URL[] { myJar.toURI().toURL() }, CustomClass.class.getClass().getClassLoader()); Class classToLoad = Class.forName("newJar.com.example.MyClass", true, loader); System.out.println(classToLoad); Method method = classToLoad.getDeclaredMethod("helloWorld"); Object instance = classToLoad.newInstance(); Object result = method.invoke(instance); } catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); }

    }

    public static void main(String[] args) { // TODO Auto-generated method stub

     File myJar = new File("Path of your jar ");//"D:\\\\ECLIPSE\\\\myjar.jar" CustomClass cls = new CustomClass(); cls.getCall(myJar);

    }

}

This is how it can make use of the jar and if the jar is on the server then can give the server path instead of the local path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM