Nashorn访问非静态Java方法 [英] Nashorn access non-static Java method

查看:180
本文介绍了Nashorn访问非静态Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我试过 http://www.doublecloud.org/2014 / 04 / java-8-new-features-nashorn-javascript-engine / https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html 如何使用Nashorn在JavaScript中实例化Java类?没有运气。他们似乎都没有像Java 1.7那样允许我,而是假设我只想访问静态函数和对象。

I've tried http://www.doublecloud.org/2014/04/java-8-new-features-nashorn-javascript-engine/ , https://docs.oracle.com/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.net.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.

https://wiki.openjdk.java.net/display/Nashorn/Using+Rhino+JSR-223+engine+with+JDK8

这篇关于Nashorn访问非静态Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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