在Java 7(1.7)中,我可以通过运行以下命令从JavaScript访问Java方法:
In Java 7 (1.7), I could access a Java method from JavaScript by running this:
ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript"); jse.eval("importClass(net.apocalypselabs.symat.Functions);"); jse.eval("SyMAT_Functions = new net.apocalypselabs.symat.Functions();"); String input = "notify(\"Foo\");"; // This is user input jse.eval("with(SyMAT_Functions){ "+input+" }");哪个会运行函数java类的notify()函数:
Which would run the notify() function from the Functions java class:
public class Functions { private Object someObjectThatCannotBeStatic; public void notify(Object message) { JOptionPane.showMessageDialog(null, message.toString()); } /* Lots more functions in here, several working with the same non-static variable */ }如何使用Nashorn引擎访问Java 1.8中的Functions类?我的目标是如果用户使用Java 1.8,则为第一个代码段运行不同的代码,同时仍然允许1.7的人使用该应用程序。
How do I access the Functions class in Java 1.8 with the Nashorn engine? My goal is to run different code for the first snippet if the user has Java 1.8, while still allowing people with 1.7 to use the app.
我试过 www.doublecloud/2014 / 04 / java-8-new-features-nashorn-javascript-engine / , docs.oracle/javase/8/docs/technotes/guides/scripting/nashorn/api.html 和如何使用Nashorn在JavaScript中实例化Java类?没有运气。他们似乎都没有像Java 1.7那样允许我,而是假设我只想访问静态函数和对象。
I've tried www.doublecloud/2014/04/java-8-new-features-nashorn-javascript-engine/ , docs.oracle/javase/8/docs/technotes/guides/scripting/nashorn/api.html , and How to instantiate a Java class in JavaScript using Nashorn? without luck. None of them seem to allow me the same thing as Java 1.7 did, instead assuming I only want to access static functions and objects.
我得到的最常见的错误:
The most common error I get:
我开始......
ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript"); jse.eval("var SyMAT_Functions;with (new JavaImporter(Packages.apocalypselabs.symat)) {" + "SyMAT_Functions = new Functions();}");...然后......
...then...
jse.eval("with(SyMAT_Functions){ "+input+" }");...吐出......
...spits out...
TypeError: Cannot apply "with" to non script object in <eval> at line number 1推荐答案
我决定编译并捆绑使用我的应用程序而不是使用Nashorn的旧Rhino解释器。
I decided to compile and bundle the "old" Rhino interpreter with my application instead of using Nashorn.
wiki.openjdk.java/display/Nashorn/Using+Rhino+JSR-223+engine+with+JDK8
更多推荐
Nashorn访问非静态Java方法
发布评论