Nashorn访问非静态Java方法

编程入门 行业动态 更新时间:2024-10-25 04:17:33
本文介绍了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.

我试过 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方法

本文发布于:2023-07-15 10:19:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110631.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   Nashorn   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!