/*
*下面是代码:拷贝然后参考上面图建立项目,可以运行,本人测试通过
*/
//PersonMain 类
package com.bobo;
public class PersonMain {
public static void main(String[] args) throws Exception {
Person person = new Person(18, 0);
String info = PersonJsEngineProcess.getInstance().getPersonaInfo(person);
System.out.printf(info);
}
}
//
package com.bobo;
import javax.script.*;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class PersonJsEngineProcess {
private static final String JS_NAME = "Person.js";
private static final String SCRIPT_NAME = "js";
private static final String FUNC_CAL_FROM_JS = "personInfo";
private ScriptEngine engine = null;
private Invocable invocableEngine = null;
public static PersonJsEngineProcess getInstance()
throws FileNotFoundException, ScriptException {
PersonJsEngineProcess pJsEgPr = new PersonJsEngineProcess();
pJsEgPr.init();
return pJsEgPr;
}
/*
* 初始化工作
* 构造一个JS执行Engine用来管理JS
*/
public void init() throws FileNotFoundException, ScriptException {
ScriptEngineManager engineMgr = new ScriptEngineManager();
engine = engineMgr.getEngineByName(SCRIPT_NAME);
try {
eval(engine, JS_NAME);
} catch (Exception e) {
e.printStackTrace();
}
invocableEngine = (Invocable) engine;
}
/*
* 根据JS的名称装在到JSengine
*/
private static void eval(ScriptEngine engine, String name) throws Exception {
InputStream is = PersonJsEngineProcess.class.getResourceAsStream(name);
engine.put(ScriptEngine.NAME, name);
engine.eval(new InputStreamReader(is));
}
/*
* 执行JS的FUNCTION
*/
public Object JsExcute(String jsFunctionName, Object o) throws Exception {
return invocableEngine.invokeFunction(FUNC_CAL_FROM_JS, o);
}
public String getPersonaInfo(Person person) throws Exception {
Object ret = JsExcute(FUNC_CAL_FROM_JS, person);
return (String) ret;
}
}
//
package com.bobo;
public class Person {
private int age;
private int sex;
public Person(int age, int sex) {
this.age = age;
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
//Person.js
function personInfo(person) {
age = person.age;
sex = person.sex;
var returnString = "defalut";
if (age <= 18) {
if (sex == 1) {
returnString = "young boy";
} else {
returnString = "young girl";
}
} else {
if (sex == 1) {
returnString = "handsome an";
} else {
returnString = "beauty girl";
}
}
return returnString;
}