在Rhino评估期间包含一个JavaScript文件 [英] Including a JavaScript file during Rhino eval

查看:50
本文介绍了在Rhino评估期间包含一个JavaScript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在另一个以Java运行的Rhino引擎正在评估的脚本"Foo"中包含一个脚本"Bar".

How would one include a script "Bar" from within another script "Foo" that is being evaluated by the Rhino Engine, running in Java.

IE,在Java中像这样设置脚本引擎:

IE, setup the script engine like this in Java:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
BufferedReader br = new BufferedReader(new FileReader(new File("Foo.js")));
engine.eval(br);

...并将以下内容放入Foo:

... and put the following in Foo:

load(["Bar.js"])

根据

According to Rhino shell documentation, that's the way to do it. But when running from Java, it's clearly not implemented:

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "load" is not defined.

@Phillip:

感谢创造性的回应.您的解决方案不能完全正常工作,因为除非使用Invocable接口,否则eval不会使解析函数可用.此外,在无法访问Java代码的情况下,它不起作用.我详细介绍了您的解决方法,并创建了一些可以在纯JS中使用的东西:

Thanks for the creative response. Your solution as is doesn't quite work because eval doesn't make the parsed function available unless the Invocable interface is used. Further, it doesn't work in cases where the Java code is not accessible. I elaborated on your workaround and created something that will work in pure JS:

首先创建一个引擎,公开Invocable接口:

First create an engine, exposing the Invocable interface:

var engine = new Packages.javax.script.ScriptEngineManager().getEngineByName("javascript");
engine = Packages.javax.script.Invocable(engine);

然后加载()"脚本

engine.eval(new java.io.FileReader('./function.js'));

此时,可以使用以下方法对函数求值:

At this point, functions can be evaluated with:

engine.invokeFunction("printHello", null);

推荐答案

我设法通过将引擎传递给自身,然后在Javascript代码中对其调用eval()来做到这一点:

I managed to do it by passing the engine to itself and then calling eval() on it inside the Javascript code:

Java代码:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.put("engine", engine);
engine.eval(new FileReader("test.js"));

test.js:

engine.eval(new java.io.FileReader('function.js'));
printHello();

function.js:

function.js:

function printHello() {
    print('Hello World!');
}

输出:

Hello World!

我不知道这是否是最优雅的方法,但是它可以工作.

I don't know if that's the most elegant way to do it, but it works.

这篇关于在Rhino评估期间包含一个JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆