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

你。 提交于 2019-12-24 03:04:20

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/24579750/can-javascript-use-classes-from-a-jar-file-non-internet-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!