简体   繁体   English

如何使用Nashorn从Java方法返回真正的JavaScript数组?

[英]How can I return a real JavaScript array from a Java method with Nashorn?

I'm writing an API to be used by some JavaScript code. 我正在编写一些API,供一些JavaScript代码使用。 Some of the methods in this API should return a real JavaScript array. 此API中的某些方法应返回真正的JavaScript数组。 Unfortunately, this doesn't work: 不幸的是,这不起作用:

// MyApi.java
public class MyApi {
    String[] returnsJavaArray();

    List<String> returnsJavaList();
}

// MyScript.js
var api = getMyApi();
var strings = api.returnsJavaArray(); // Returns some kind of proxy
strings = api.returnsJavaList(); // Also a proxy

While the proxies support basic things like strings[i] , I need them to be actual arrays in order to use some Array polyfills. 虽然代理支持像strings[i]这样的基本内容,但我需要将它们作为实际数组才能使用某些Array polyfill。 What's the best way to do this in Nashorn? Nashorn最好的办法是什么?

My only idea so far is to write a JavaScript wrapper of the whole MyApi and wrap the results with Java.from(api.returnsJavaArray()) but that's pretty tedious. 到目前为止,我唯一的想法是编写整个MyApi的JavaScript包装器并使用Java.from(api.returnsJavaArray())包装结果, Java.from(api.returnsJavaArray())非常繁琐。

You should make you API return a string of js. 你应该让你的API返回一串js。 Then, in your js file, you can call 然后,在你的js文件中,你可以打电话

eval(stringOfJsReturnFromServer); 

To make your script run 使您的脚本运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM