开发者

Allowing Java's ScriptEngineManager to access certain Java Methods

开发者 https://www.devze.com 2023-03-31 01:09 出处:网络
Is it possible to access Java methods from inside ScriptEngineManager. I found out how to use the Invocable invoke function method, but now I need the opposite to happen.

Is it possible to access Java methods from inside ScriptEngineManager.

I found out how to use the Invocable invoke function method, but now I need the opposite to happen.

public class Main {
  public static void main (String[] args) throws Exception {
    String source = "var results = system.foo('example');            \n" +
                    "                                                \n" +
                    "if(results == \"hello\") {                      \n" +
                    "  print(\"ding dong.\");                        \n" +
                    "}                                               \n";
    ScriptEngine engine = new ScriptEngineManager().get开发者_StackOverflow中文版EngineByName("JavaScript");
    engine.eval(source);
  }
}

public class System {
  public static String foo (String x) throws Exception {
    // do something with x
    return("hello");
  }
}

So when I run system.foo it should run the method in System.foo.


Doing this using Mozilla Rhino is much easier. Say your wanted to expose System.out to your scripts:

Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
Object wrappedOut = Context.javaToJS(System.out, scope);
ScriptableObject.putProperty(scope, "out", wrappedOut);

Then in JavaScript:

var hello = "Hello World";
out.println(hello);

You can also expose individual Java methods by extending the Function class in the Rhino library and they exposing it to your scripts in a similar fashion.

0

精彩评论

暂无评论...
验证码 换一张
取 消