How to access Java Enums from Javascript (Java 1.8)

孤者浪人 提交于 2019-12-06 04:54:37

问题


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

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.

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.

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

Thanks!


回答1:


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);

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



来源:https://stackoverflow.com/questions/28974548/how-to-access-java-enums-from-javascript-java-1-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!