Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Rhino JS to see Java class

I'm playing with Rhino, and I've had success using Java classes from the stdlib, but not from Java code I compiled here.

For example, this works fine:

print(new java.util.Date());

But with NanoHTTPD (single .java file, no namespace, same folder), I'm having no luck at all:

js> new Packages.NanoHTTPD()
js: "<stdin>", line 4: uncaught JavaScript runtime exception: TypeError: [JavaPackage NanoHTTPD] is not a function, it is object.
    at <stdin>:4

I'm sure it's something simple. What am I missing?

EDIT: I'm launching it like this:

$ CLASSPATH=. java -jar rhino.jar

or this:

$ java -classpath . -jar rhino.jar

Or I moved NanoHTTPD.java into the folder "./nano", added package nano; to the top of the file, compiled it, and then replaced "." with "nano" in the above classpath assignments.

Any way I do it, from in the interpreter I see:

js> java.lang.System.getProperty("java.class.path")
/Users/me/blah/rhino.jar
like image 915
Ken Avatar asked Dec 29 '22 03:12

Ken


1 Answers

You need to run Rhino like this:

java -cp /path/to/rhino/js.jar:. org.mozilla.javascript.tools.shell.Main

This adds the current directory to the classpath. Using -jar clobbers the classpath. (The classpath separator depends on your OS.)

Then try

js> Packages.NanoHTTPD
[JavaClass NanoHTTPD]

If it says [JavaPackage NanoHTTPD], it means it hasn't found a class by that name.

You can't instantiate NanoHTTPD anyways, so I'm guessing you want to try Packages.NanoHTTPD.main([]) or something.

like image 64
erjiang Avatar answered Feb 14 '23 11:02

erjiang