Search code examples
javascriptingjava-scripting-engine

If I bind an object of one of my classes to a scripting engine, how can I access it as an object of that class from withing the scripting engine?


I want to be able to pass an object into ScriptEngine via put() and be able to access its properties and methods from within the scripting engine.

e.g

public class MyClass {
    String getName() { return "abc"; }
}

MyClass my = new MyClass();
engine.put("abc", my);

How can I do this?


Solution

  • Here is a complete working example with JavaScript. As I mentioned in the comment, you have to make sure that your methods are public.

    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    public class JavaScriptEngineSample {
    
        public static class MyClass {
            private String name;
    
            public String getName() { return name; }
            public void setName(final String name) { this.name = name; }
        }
    
        public static void main(final String[] args) throws ScriptException {
            final MyClass my = new MyClass();
            my.setName("Input");
    
            final ScriptEngineManager factory = new ScriptEngineManager();
    
            // you could also use 'javascript' here, I'm using 'nashorn' to visualize that I'm using the new Java 8 Engine
            final ScriptEngine engine = factory.getEngineByName("nashorn");
    
            engine.put("my", my);
    
            String script = "java.lang.System.out.println(my.getName());";
            script += "my.setName('Output');";
    
            engine.eval(script);
    
            System.out.println(my.getName());
        }
    }