Java Nashorn expose java class (not instance) to javascript

1.1k views Asked by At

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

There are 2 answers

1
A. Sundararajan On

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!

0
A. Sundararajan On

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