Java Nashorn JSObject将函数设置为成员

时间:2016-03-13 18:30:40

标签: java nashorn

我正在使用nashorn脚本引擎并且遇到了JSObject接口的问题。 我已经创建了一个基类,通过HashMap为成员添加函数manuelly:

public abstract class EngineObject extends AbstractJSObject {
    private Map<String, Object> members;

    public EngineObject() {
        this.members = new HashMap<>();
    }

    public abstract String getName();

    public void initialize(Engine engine) {
    }

    @Override
    public Object getMember(String name) {
        return this.members.get(name);
    }

    @Override
    public void setMember(String name, Object value) {
        this.members.put(name, value);
    }

    @Override
    public boolean hasMember(String name) {
        return this.members.containsKey(name);
    }

    @Override
    public void removeMember(String name) {
        this.members.remove(name);
    }
}



public class MyObject extends EngineObject {
    this.setMember("test", (Runnable) () -> {
        System.out.println("Test");
    });
}

//JavaScript - works
MyObject.test.run();

//JavaScript -- doesn't work
MyObject.test();

如何将一个函数添加到javascript将其识别为函数的hashmap中? 我如何通过getMember(来自HashMap)调用函数?

1 个答案:

答案 0 :(得分:2)

正如“aventurin”所提到的,你的想法是正确的 - 但你的代码是不完整的。简单的可编辑,可运行的示例:

import javax.script.*;
import jdk.nashorn.api.scripting.*;

public class Main {
   public static void main(String[] args) throws Exception {
       JSObject jsobj = new AbstractJSObject() {
           @Override
           public Object getMember(String name) {
               // return a Runnable for "func"
               if (name.equals("func")) {
                  return new Runnable() {
                      @Override
                      public void run() {
                         System.out.println("in run!");
                      }
                  };
               }
               return null;
           }
       };

       ScriptEngineManager m = new ScriptEngineManager();
       ScriptEngine e = m.getEngineByName("nashorn");
       e.put("obj", jsobj);
       e.eval("obj.func()");
   }
}