java8 新特性 v8 nashorn 引擎(五)

简单的javascript 作为文本输出

ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        String js;

        js = "var map = Array.prototype.map \n";
        js += "var names = [\"john\", \"jerry\", \"bob\"]\n";
        js += "var a = map.call(names, function(name) { return name.length() })\n";
        js += "print(a)";

        try {
            engine.eval(js);
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("nashorn");
        try {
            jse.eval("print('Hello DoubleCloud! - inline');");
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


执行javascript 文件


ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine jse = scriptEngineManager.getEngineByName("nashorn");
        System.out.println("current dir: " + new File(".").getAbsoluteFile());
        try {
            jse.eval(new FileReader("./src/com/test/zcw/java/script.js"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

js文件语句:eval("print('Hello DoubleCloud! - inline');")


调用javascript 函数

 ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
          ScriptEngine jse = scriptEngineManager.getEngineByName("nashorn");
        
          jse.eval(new FileReader("./src/com/test/zcw/java/script.js"));
        
          Invocable runner = (Invocable) jse;
        
          Object result = runner.invokeFunction("hi", "DoubleCloud! - via javascript function");
          System.out.println(result);
          System.out.println(result.getClass());

函数内容:

var hi = function(name)
{
  return 'Hi ' + name;
}


javascript调用java

var hw = Java.type('com.test.zcw.java8.JSNashorn');

var result = hw.sayHi("DoubleCloud - calling Java method in JS.");
print(result);

java

static public String sayHi(String name) {
        return "Hi " + name;
    }

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine jse = scriptEngineManager.getEngineByName("nashorn");
        jse.eval(new FileReader("./src/com/test/zcw/java/java8/script.js"));


你可能感兴趣的:(java,类技术总结)