如何在Java中将.js文件加载到Rhino上下文中 [英] How to load .js files into a Rhino context in Java

查看:93
本文介绍了如何在Java中将.js文件加载到Rhino上下文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的情况:

我可以访问Java类中的Rhino Context对象。我想阅读一堆.js文件并将它们传递给Rhino上下文以对它们进行评估。我真的不想在脚本上下文中使用.js文件中的函数,因为我只是在.js文件中声明的变量可用(这是工具验证的一种问题)。

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

理想情况下,我会读入并尝试一次评估每个文件,而不是逐行评估。我注意到Context中有一个方法(参见 Rhino API )调用 evaluateReader()。我的第一个猜测是我应该获取我想要加载的所有文件,仔细检查它们,然后调用这个方法为每个文件传递某种读者对象,很棒,现在它们都在我的脚本环境中。

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.

所以,假设我在那里正确的轨道,有人能告诉我在Java脚本环境中使用.js文件是否有任何好的做法,或者如果有的话这是一个更好的方法,或者你以其他方式做到了,等等?

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?

这里没有寻找实施细节,只是来自其他可能做过这个的人的反馈已经在他们的一些代码中。使用Java编写脚本语言对我来说是新的。

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.

推荐答案

你知道 Rhino在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);

如果你想在Java 5中使用它,你必须单独下载 API。您可以从 scripting.dev.java.net 获取许多流行脚本语言的引擎。

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.

这篇关于如何在Java中将.js文件加载到Rhino上下文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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