一个对Nashorn脚本引擎很详细地介绍: http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
下面是我测试的小例子,模拟在游戏中伤害计算脚本化:
ScriptTest.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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:
1
2
3
4
5
6
7
8
|
package
com.zl1030.ScriptTest;
public
interface
Test1 {
public
int
getLength(String msg);
public
ScriptResult calc(A a, A b);
}
|
ScriptResult.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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;
}
|