/**
* Object And Method Test
* @throws Exception
*/
@Test
public static void objectAndMethodTest() throws Exception{
//创建脚本引擎管理器
ScriptEngineManager manager = new ScriptEngineManager();
//通过脚本名称获取
ScriptEngine engine = manager.getEngineByName("JavaScript");
//指定js脚本文件
File shellFile = new File("D:/test/index.js");
//js脚本文件读取
FileReader fileReader = new FileReader(shellFile);
//执行
engine.eval(fileReader);
// javax.script.Invocable 是一个可选的接口,注意:ScriptEngine实现了Invocable接口
Invocable inv = (Invocable) engine;
// 执行js 中 methodTest方法
inv.invokeFunction("methodTest");
// 获取调用js对象
Object phone = engine.get("phone");
// 执行phone对象的名为phoneMethod的方法、传递给过程或函数的参数
inv.invokeMethod(phone, "phoneMethod","华为Mate2000");
// 执行js中referenceObject方法,传ScriptEntity对象
ScriptEntity scriptEntity = new ScriptEntity();
scriptEntity.setId(1457225);//编号
scriptEntity.setNumber(1000);//数量
scriptEntity.setStock(200);//库存
scriptEntity.setOrder(99);//订单
scriptEntity.setAddress("XX省XX市XX区XX");//地址
inv.invokeFunction("referenceObject",scriptEntity);
}
/**
* main
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
objectAndMethodTest();
}/***************************************分割线*************************************/
/** Hello JS **/
var content = "Hello js";
function getPrint(){
print(content);
}
getPrint();
/** 运算符 Test **/
var a = 10; var b = 2;
function myFunction() {
print(a+b);
print(a-b);
print(a*b);
print(a/b);
}
myFunction();
/** Method Test **/
function methodTest(){
print("Method Test!!!");
}
/** date **/
var now = new Date();
var year = now.getFullYear(); //得到年份
var month = now.getMonth();//得到月份
var date = now.getDate();//得到日期
var day = now.getDay();//得到周几
var hour = now.getHours();//得到小时
var minu = now.getMinutes();//得到分钟
var sec = now.getSeconds();//得到秒
var MS = now.getMilliseconds();//获取毫秒
/** Object And Method Test **/
var phone = new Object();
phone.name = "华为Mate20";
phone.price = "2999";
phone.color = "蓝色";
phone.nowDate = year + "-" + month + "-" + date + "-" + day + " " + hour + ":" + minu + ":" + sec;
phone.desc = year + "年上市!!!";
phone.phoneMethod = function(args){
phone.name = args;
print(phone.name + "," + phone.color + "," + phone.nowDate + "," + phone.desc);
}
/** Parameter Transfer Test **/
function referenceObject(scriptEntity){
print(scriptEntity.getId() + "," + scriptEntity.getNumber() + "," + scriptEntity.getStock() + "," + scriptEntity.getOrder() + "," + scriptEntity.getAddress());
}