JavaScript date delivery for Nashorn script

I am working on a Java API that allows users to write scripts and access a specific set of methods that are passed (as an API object) by the Nashorn script engine.

I want to call getDate () in JavaScript, which will return some arbitrary date (like the native JavaScript date) provided by Java.

I tried just putting org.java.util.Date on an API object, but this will not behave like a JS date. The goal is to make it as simple as possible for end users who have experience with JS.

Java example:

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 ClassFilter
        ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(new MyClassFilter());
        ((Invokable) engine).invokeFunction("entryPoint", new MyAPI());
    }

JavaScript example

function entryPoint(myApi){
    var date = myApi.getDate();
    myApi.log(date.getMinutes());
}
+2
source share
2 answers

Nashorn , , Javascript. java.util.Date != new Date() ( javascript). jdk.nashorn.internal.objects.NativeDate JS.

, NativeDate, Java, Javascript MyApi, JS-, getDate().

var MYAPI_JAVASCRIPT = {
    log: function() {
        print(arguments);
    },
    getDate: function() {
        return new Date();
    }
}

.


, NativeDate Java-, :

public NativeDate getDate() {
    return (NativeDate) NativeDate.construct(true, null);
}
+2

jdk.nashorn.internal. * nashorn. , JDK. , , Java- , SecurityException! jdk jdk9 nashorn, javac jdk9!

JS- ( 1) "ug_". Java, API, jdk.nashorn.api.scripting.

"" - javax.script.ScriptEngine nashorn, - :

import jdk.nashorn.api.scripting.*;

..

public Object getDate() {
    // get JS Date constructor object - you can get once and store
    // as well/
    JSObject dateConstructor = (JSObject) engine.eval("Date");
    // now do "new" on it
    return dateConstructor.newObject();
}

JS script "getDate()" API JS . , newObject ( Java).

+3

All Articles