1

I was using ClearScript with .NET to expose Classes to Javascript. I used this to expose class (not instance of class to JS) : engine.AddHostType("Worker", typeof(Worker)); So I could use var x = new Worker(); In javascript;

Now in Nashorn with Java this does not work. I am only able to expose instance of class like this : factory.getBindings().put("Worker", new Worker());

Is there a way to expose class type to javascript with Nashorn.

Thank you!

2 Answers 2

3

Your script can directly access any Java class by fully qualified name such as

var Vector = Java.type("java.util.Vector");
// or equivalently:
var Vector = java.util.Vector;
// Java.type is better as it throws exception if class is not found

If you don't want the script to directly refer to your Java class or perhaps you want to provide a different name, you could do something like this:

import javax.script.*;

public class Main {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager m = new ScriptEngineManager();
        ScriptEngine e = m.getEngineByName("nashorn");

        // eval "java.util.Vector" to get "type" object and then
        // assign that to a global variable.
        e.put("Vec", e.eval("java.util.Vector"));

        // Script can now use "Vec" as though it is a script constructor
        System.out.println(e.eval("v = new Vec(); v.add('hello'); v"));
    }
}

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! @A. Sundararajan
1

If you already have a java.lang.Class object of the type you want to expose to script, you could do the following:

import javax.script.*;
import java.util.Vector;

public class Main {
    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager m = new ScriptEngineManager();
        ScriptEngine e = m.getEngineByName("nashorn");

        // expose a java.lang.Class object to script
        e.put("Vec", Vector.class);

        // script can use "static" property to get "type" represented
        // by that Class object.
        System.out.println(e.eval("v = new Vec.static(); v.add('hello'); v"));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.