0

Using Vert.x JavaScript (3.8.4), I want to dynamically load a JAR file at runtime. This is necessary because that file might not exist when my Vert.x application gets started. Ideally, I would like to be able to use code like this:

// load custom JAR file
requireJar("path/to/dynamic.jar");
// use class from dynamically loaded package
var instance = new com.mydynamicpackage.MyCustomClass();

How can I achieve this?

xpages-noob
  • 1,569
  • 1
  • 10
  • 37

2 Answers2

0

You might find this answer to be helpful:

How to access external JAR files from JavaScript using Rhino and Eclipse?

Another approach that is valid would be to provide the jar with other means, i.e. not via a javascript implementation, to check afterwards, if it is available and then deal with the case if it is not.

    java.lang.Class.forName( 'com.mydynamicpackage.MyCustomClass' )

This will throw an error, if MyCustomClass does not exist.

Loading jars at runtime might not be a good idea if you cannot determine they are loaded from a not trustworthy source. This is at least true for the java world.

Erunafailaro
  • 1,835
  • 16
  • 21
0

Based on this answer, I have created the following JavaScript function for dynamically loading a class from a JAR file:

var requireJavaClass=(function(){
    var method=java.net.URLClassLoader.class.getDeclaredMethod("addURL",java.net.URL.class);
    method.setAccessible(true);
    var cache={};
    var ClassLoader=java.lang.ClassLoader;
    var File=java.io.File;
    return function(classname,jarpath){
        var c=cache[classname];
        if (c) return c;
        if (jarpath) {
            var cl=ClassLoader.getSystemClassLoader();
            method.invoke(cl,new File(jarpath).toURI().toURL());
            cl.loadClass(classname);
        }
        return cache[classname]=Java.type(classname);
    }
})();

The equivalent to the snippet I posted in the my question would be:

var MyCustomClass=requireJavaClass("com.mydynamicpackage.MyCustomClass","path/to/dynamic.jar");
var instance = new MyCustomClass();

So far, I have only tested this with Vert.x 3.8.5 running in JRE8, i.e. I can't say if this also works in older Vert.x versions or with JRE9+.

xpages-noob
  • 1,569
  • 1
  • 10
  • 37