Java 脚本引擎导入我的类不起作用
一段代码值得用 1000 字来解释:-)
package jasim;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JSTest {
public static void main(String[] args) throws ScriptException {
ScriptEngine jse = new ScriptEngineManager().getEngineByExtension("js");
jse.eval("println(new jasim.JSTest().toString)");
}
@Override
public String toString() {
return "JSTest Object";
}
}
该代码将失败,并出现以下异常:
Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "jasim" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
如何将我自己的类导入到 ScriptEngine 中?
A code is worth 1000 words of explaining it :-)
package jasim;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JSTest {
public static void main(String[] args) throws ScriptException {
ScriptEngine jse = new ScriptEngineManager().getEngineByExtension("js");
jse.eval("println(new jasim.JSTest().toString)");
}
@Override
public String toString() {
return "JSTest Object";
}
}
This code will fail with the below exception:
Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "jasim" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
How do I import my own classes into the ScriptEngine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 Mozilla Rhino 文档后,解决方案是使用:
importPackage (Packages.jasim)
在脚本中,或使用new Packages.jasim.JSTest()
Sun 文档中关于 ScriptingEngine 文档中的 importPackage 的说明不太清楚。
After looking at the Mozilla Rhino docs, the solution is either to use:
importPackage(Packages.jasim)
within the script, or to usenew Packages.jasim.JSTest()
This is not so clear in the Sun docs regarding the importPackage in the ScriptingEngine docs.
与导入 javax.script.ScriptEngine; 的方式相同...
只需确保您的类位于 CLASSPATH 中
The same way you import
javax.script.ScriptEngine;
...Just make sure your classes are in the CLASSPATH