java 脚本引擎_Java8 新JavaScript脚本引擎Nashorn小试

下面是我测试的小例子,模拟在游戏中伤害计算脚本化:

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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值