2

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.

3
  • define import with regard to what you tried and define doesn't work Commented Jul 4, 2014 at 19:17
  • 1
    Where the heck are you running the javascript then? Node.js? Through Rhino? You need to be specific. Commented Jul 4, 2014 at 19:19
  • @Gimby Please see the update above despite the question now being answered. Commented Jul 6, 2014 at 18:44

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Could you clarify how you got "Packages" defined in you javascript environment?
I forget I'm sorry but it might be a keyword stackoverflow.com/questions/6167418/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.