如何从嵌入式Rhino载入本地文件? [英] How can I load a local file from embedded Rhino?

查看:234
本文介绍了如何从嵌入式Rhino载入本地文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rhino的 context.evaluateString()从Java内部运行一些简单的JavaScript。它是嵌入Javascript指南

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);

我不确定这是当前的最佳实践,因为Rhino的主要文档似乎是

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.

我希望能够引用工作目录中的库-我看到 Rhino shell支持 load ,但我不支持不会认为这在嵌入引擎中起作用。

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.

这可能吗?它记录在任何地方吗?理想情况下,我希望能够仅调用 load('other.js')之类的东西,并使它搜索我指定为全局属性的目录。

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:

eval("" + Packages.org.apache.commons.io.FileUtils.readFileToString(
  new java.io.File("/the/local/root", "script.js");
));

{那 + ... 这是解决该错误的方法-如果您 eval() Java String (例如从 readFileToString 调用),而无需手动将其强制为JavaScript本机字符串,则似乎没有任何反应。呼叫只是默默失败。 }

{ That "" + ... is how I work around the bug -- if you eval() a Java String (such as is returned from the readFileToString call) without manually coercing it to a JavaScript native string, nothing appears to happen. The call just silently fails. }

这会盲目读取任意文件并进行评估-当然,这是当您 eval()是Java方面的,所以我不必为此担心太多。

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!

这篇关于如何从嵌入式Rhino载入本地文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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