Here is my situation:
I have access to a Rhino Context object in a Java class. I want to read in a bunch of .js files and pass them along to the Rhino context to have them evaluated. I'm not really interested in having the functions in the .js files available in the scripting context so much as I am in just having the variables that are declared in the .js files available (this is a tooling validation kind of issue).
Ideally I would read in and try to evaluate each file all at once, not line by line. I noticed there is a method in Context (see Rhino API) called evaluateReader()
. My first guess is I should get all the files I want to load, go through them all, and call this method passing in some kind of reader object for each one, and great, now they're all in my scripting context.
So, assuming that I am on the right track there, can anyone tell me if there are any good practices to follow for using .js files in Java scripting contexts, or if there is a better way of doing it, or you did it some other way, etc?
Not looking for implementation details here, just feedback from other people that might have done this already in some of their code. Messing with scripting languages from Java is new to me.
Are you aware that Rhino ships in Java 6?
String javaScriptExpression = "sayHello(name);";
Reader javaScriptFile = new StringReader(
"function sayHello(name) {\n"
+ " println('Hello, '+name+'!');\n" + "}");
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory
.getEngineByName("JavaScript");
ScriptContext context = engine.getContext();
context.setAttribute("name", "JavaScript",
ScriptContext.ENGINE_SCOPE);
engine.eval(javaScriptFile);
engine.eval(javaScriptExpression);
If you want to use it with Java 5, you'll have to download the API separately. You can get engines for many popular scripting languages from scripting.dev.java.net.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With