Permitir que ScriptEngineManager de Java acceda a ciertos métodos de Java

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().getEngineByName("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.

preguntado el 28 de agosto de 11 a las 01:08

If you are looking for a JavaScript engine I would use the latest version of Rhino. The version that is packaged with the JRE is old. -

I need to be able to specify what classes they can access. -

1 Respuestas

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

Luego en 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.

Respondido 28 ago 11, 20:08

So does this mean the not all methods will be exposed? - Mark

You can expose an object or you can wrap a method by implementing the Function object in the Rhino library. - babsher

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.