Java执行JS脚本Demo

/**
 * 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());

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值