向Nashorn脚本提供JavaScript日期 [英] Supply JavaScript date to Nashorn script
问题描述
我正在研究Java中的API,该API允许用户编写脚本并访问Nashorn脚本引擎传入的一组特定方法(以API对象的形式)。
I am working on an API in Java that allows users to write scripts and access a specific set of methods that are passed in (in the form of an API object) by the Nashorn script engine.
我想在JavaScript中调用函数getDate(),该函数将返回Java端提供的一些任意日期(作为本机JavaScript日期)。
I want to, in the JavaScript, call a function getDate(), which will return some arbitrary date (as a native JavaScript date) that's provided from the Java side.
我曾尝试将org.java.util.Date放在API对象上,但这不会像JS日期那样。目标是使具有JS经验的最终用户尽可能地简化此操作。
I have tried simply putting an org.java.util.Date on the API object, but that won't behave like a JS date. The goal is to make this as simple as possible for end-users who are experienced with JS.
Java示例:
public class MyAPI {
public void log(String text){
System.out.println(text);
}
public Date getDate(){
// Return something that converts to a native-JS date
}
public static void main(){
// MyClassFilter implements Nashorn's ClassFilter
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(new MyClassFilter());
((Invokable) engine).invokeFunction("entryPoint", new MyAPI());
}
JavaScript示例
JavaScript example
function entryPoint(myApi){
var date = myApi.getDate();
myApi.log(date.getMinutes());
}
推荐答案
Nashorn引擎具有对象在内部使用,它们表示Javascript对象。如您所料, java.util.Date!= new Date()
(在javascript中)。引擎使用名为 jdk.nashorn.internal.objects.NativeDate
的类表示其JS日期。
The Nashorn engine has objects it uses internally which represent the Javascript objects. As you have guessed the java.util.Date != new Date()
(in javascript). The engine uses a class called jdk.nashorn.internal.objects.NativeDate
to represent its JS date.
如果我要进行构建,则不会在Java中构建 NativeDate
,而是在其中使用包装器 MyApi
对象的Javascript,其中将包含其他一些本机JS方法,例如 getDate()
。
If I were building this out I would not have the NativeDate
constructed in the Java but instead have a wrapper in Javascript for the MyApi
object which would contain a few other native JS methods, such as getDate()
.
var MYAPI_JAVASCRIPT = {
log: function() {
print(arguments);
},
getDate: function() {
return new Date();
}
}
然后可以将该对象作为方法参数传递。
You could then pass that object as the method parameter.
但是,如果您确实打算在自己的计算机上使用 NativeDate
然后,您可以像这样构造Java代码:
However if your really set on using the NativeDate
in your Java code then you can construct one like so:
public NativeDate getDate() {
return (NativeDate) NativeDate.construct(true, null);
}
这篇关于向Nashorn脚本提供JavaScript日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!