I'm using Rhino's context.evaluateString()
to run some simple JavaScript from inside of Java. It's textbook right out of the Embedding Javascript guide:
String script = // simple logic
Context c = new ContextFactory().enterContext();
ScriptableObject scope = context.initStandardObjects();
Object o = context.evaluateString(scope, script, "myScript", 1, null);
ScriptableObject result = Context.jsToJava(o, ScriptableObject.class);
I'm not sure this is the current best-practice, because the main Rhino docs appear to be down, but it's working so far.
I'd like to be able to refer to a library in the working directory -- I see that Rhino shell supports load
but I don't think this works in the embedding engine.
Is this possible? Is it documented anywhere? Ideally, I'd like to be able to just call something like load('other.js')
and have it search directories I specify as a global property.
I have a sort-of answer that I don't really like, not least because it exposes what I'm pretty sure is a Rhino bug that drove me crazy for the last half hour:
{ That
"" + ...
is how I work around the bug -- if youeval()
a JavaString
(such as is returned from thereadFileToString
call) without manually coercing it to a JavaScript native string, nothing appears to happen. The call just silently fails. }This blindly reads an arbitrary file and evals it -- of course, this is what you do when you
eval()
from the Java side, so I don't worry about it too much.Anyway, it's not elegant for a number of reasons, but it works. I'd love to hear a better answer!