如何从 Javascript (Java 1.8) 访问 Java 枚举 [英] How to access Java Enums from Javascript (Java 1.8)

查看:33
本文介绍了如何从 Javascript (Java 1.8) 访问 Java 枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 1.7 中,在移除之前,可以使用包"以下列方式从浏览器查看的 HTML 页面上的 Javascript 访问 Java 枚举:

In Java 1.7, prior to it's removal, one could use 'Packages' to access Java Enums in the following way from Javascript on an HTML page viewed a browser:

var enumvar1 = document.appletid.Packages.com.mycompany.MyClass$MyEnumYesNo.YES
var enumvar2 = document.appletid.Packages.com.mycompany.MyClass$MyEnumYesNo.NO

我正在升级这些 HTML 页面以使用 Java 1.8(现在使用 Nashorn javascript 引擎),但我似乎无法弄清楚如何访问 Enum 成员.

I'm upgrading these HTML pages to use Java 1.8 (which now uses the Nashorn javascript engine), and I cannot seem to figure out how to access the Enum members.

我已经重写了 Java 小程序,将一个新的 MyClass 对象返回给一个 javascript 变量,并且我可以从 JavaScript 变量访问 MyClass 中的所有方法和字段,但是我无法弄清楚获取该变量的语法枚举.错误属于属性为空/未定义"类型.我尝试了包名、类名、类保存变量和小程序 ID 变量的各种组合.

I've rewritten the Java applet to return a new MyClass object to a javascript variable, and I can access all the methods and fields in MyClass from the JavaScript variable, but I can't figure out the syntax to get at the Enums. The errors are of the type "property is null/undefined". I've tried various combinations of the package name, class name, variable holding the class, and applet ID variable.

我在谷歌搜索中没有找到任何关于 Java 1.8 的示例,尽管在阅读 Oracle 的 Nashorn 文档时,它暗示可以访问枚举.

I haven't found any examples for Java 1.8 in googling around, although in reading the Nashorn documentation from Oracle, it implies that Enums can be accessed.

有人可以提供示例语法吗?可能我只是忽略了一些简单的事情......

Could someone provide an example syntax? Probably something simple that I am just overlooking...

谢谢!

推荐答案

Nashorn 引入了全局函数 Java.type() 来与 Java 类进行交互.http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html

Nashorn introduces global function Java.type() to interact with Java classes. http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html

这是一个如何使用它的示例

Here is an example how you can use it

var retPolicy = Java.type("java.lang.annotation.RetentionPolicy");
print(retPolicy.RUNTIME);

此外,如果您正在寻找从 Rhino 迁移到 Nashorn 的方法,请考虑遵循手册 https://wiki.openjdk.java.net/display/Nashorn/Rhino+Migration+Guide

Also, if you're looking the ways to migrate to Nashorn from Rhino consider following manual https://wiki.openjdk.java.net/display/Nashorn/Rhino+Migration+Guide

这篇关于如何从 Javascript (Java 1.8) 访问 Java 枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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