标签:java 脚本 nashorn javascript
一个对Nashorn脚本引擎很详细地介绍: http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
下面是我测试的小例子,模拟在游戏中伤害计算脚本化:
ScriptTest.java:
package com.zl1030.ScriptTest; import java.io.FileReader; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class ScriptTest { public static void main(String[] args) { try { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("nashorn"); String scriptPath = System.getProperty("user.dir") + "/Scripts/Test1.js"; engine.eval(new FileReader(scriptPath)); Invocable invocable = (Invocable) engine; Test1 test1 = invocable.getInterface(Test1.class); ScriptResult result = (ScriptResult) test1.calc(new A(), new A()); System.out.println(test1.getLength("abcdefg")); System.out.println(result.getDamage() + " " + result.getTarget().getA() + " " + result.isResult()); } catch (Exception e) { e.printStackTrace(); } } }
Test1.java:
package com.zl1030.ScriptTest; public interface Test1 { public int getLength(String msg); public ScriptResult calc(A a, A b); }
ScriptResult.java:
package com.zl1030.ScriptTest; public class ScriptResult { private A target; private boolean result; private int damage; public A getTarget() { return target; } public void setTarget(A target) { this.target = target; } public boolean isResult() { return result; } public void setResult(boolean result) { this.result = result; } public int getDamage() { return damage; } public void setDamage(int damage) { this.damage = damage; } }
A.java:
package com.zl1030.ScriptTest; public class A { private int a = 0; private int b = 0; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } }
Test1.js:
var ScriptResultClass=Java.type(‘com.zl1030.ScriptTest.ScriptResult‘); function getLength(msg) { return msg.length; } function calc(a, b) { a.setA(1); a.setB(2); var result = new ScriptResultClass(); result.setTarget(a); result.setDamage(10); result.setResult(true); return result; }
本文出自 “zl1030的记录” 博客,请务必保留此出处http://zl1030.blog.51cto.com/274507/1660007
Java8 新JavaScript脚本引擎Nashorn小试
标签:java 脚本 nashorn javascript
原文地址:http://zl1030.blog.51cto.com/274507/1660007