Loading

java 执行 javascript 代码

package com.ruoyi.project.front.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.IdUtils;
import com.ruoyi.common.utils.StringUtils;
//import javafx.util.Pair;
//import org.apache.commons.lang3.tuple.ImmutablePair;
//import org.apache.commons.lang3.tuple.MutablePair;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.front.domain.*;
import com.ruoyi.project.front.service.*;
import com.ruoyi.project.material.domain.QuoteMatSpecs;
import com.ruoyi.project.material.service.IQuoteMatSpecsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.web.domain.AjaxResult;
// groovy 动态执行
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
//
import javax.script.*;
import javax.servlet.http.HttpServletRequest;


   public void test1()
    {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        String script = "(1+0.1 * (F/100) * T)*P0";
        CompiledScript JSFunction = null;
        try {
            JSFunction = compilable.compile(script);
            bindings.put("F", 2.5);
            bindings.put("T", 30);
            bindings.put("A", 100);
            bindings.put("P0", 100);
            Object result = JSFunction.eval(bindings);
            System.out.println(result);
        } catch (ScriptException e) {
            //e.printStackTrace();
        }
    }

    public  void test2()
    {
        //示例一
        //GroovyShell shell = new GroovyShell();
        //Object result = shell.evaluate("(1+5)/2");
        //System.out.println(result);

        Binding binding = new Binding();
        binding.setVariable("F",2.5);
        binding.setVariable("T",30);
        binding.setVariable("A",100);
        binding.setVariable("P0",100);
        binding.setVariable("language", "Groovy");
        GroovyShell shell = new GroovyShell(binding);
        Object F1 =shell.evaluate("P1=(1+0.1 * (F/100) * T)*P0; return P1 ");
        System.out.println(F1);
        Object F2 =shell.evaluate("P1=P0*(0.055*0.20+1.0011)+A; return P1 ");
        System.out.println(F2);
    }
        

 

posted @ 2020-09-03 11:01  Sam Xiao  阅读(631)  评论(0编辑  收藏  举报