Can JavaScript use classes from a jar file (Non Internet Use)

Kyle Bridenstine picture Kyle Bridenstine · Jul 4, 2014 · Viewed 9.4k times · Source

I have an API in a jar file but how can I use the classes from the jar in JavaScript? When I try importing them,

    conf = Packages.abcapi.Config;
    var cfg = new conf.Config();

It doesn't work. This is not going to be used in a browser or over the internet.

UPDATE:

I'm extending our API to all JSR-223 Scripting Languages using Java ScriptEngine. Inside the Java application I read a JavaScript File and then execute the file using ScriptEngine. I need for the JavaScript File to use classes from the API which lays in a jar file. I try setting the jar in the classpath when running the ScriptEngine but it still doesn't find the classes using the above code. This works fine in Jython though, as in Jython has no problem using the classes in the jar file after setting the jar in the class path.

Answer

Kyle Bridenstine picture Kyle Bridenstine · Jul 5, 2014

I am reading JavaScript files then executing them using Java ScriptEngine. Add the jar to your class path when you run the Java code that's going to execute the JavaScript like this,

    java -cp ./;C:\Location\Of\The\Jar\File\abc.jar MainClass

Then inside JavaScript you can get the package from within that jar and set the package to a variable. Then when you want to use a Class from that package just prefix the class name with the variable and then a . like this,

    myvariable = Packages.abc.foo.pack.name;

    var foo = new myvariable.ClassFromTheJarFile("arg1","arg2");

    foo.doSomething();

    var fooSister = new myvariable.AnotherCLassFromTheJarFile("arg1");

    fooSister.doSomthingFromThisClass();

What I did wrong was try to import the class directly from the package like this,

    myvariable = Packages.abc.foo.pack.name.ClassFromTheJarFile;

So only import the package and not the classes. To clarify you do not need to use the Java *.

This is not being using in a browser or over the internet. Here is another link that uses a jar from a URL location and it might be helpful to someone http://mozilla-firefox-extension-dev.blogspot.com/2004/11/calling-java-code-in-custom-jars-from.html