用户工具


maven

        <dependency>
            <groupId>org.mvel</groupId>
            <artifactId>mvel2</artifactId>
            <version>2.2.6.Final</version>
        </dependency>

main

import org.mvel2.MVEL;
import org.mvel2.compiler.CompiledExpression;
import org.mvel2.compiler.ExpressionCompiler;

import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class test
{
    public static void main(String[] args) throws Exception
    {
        preCompile();
        explainScript();
        scriptEngineManager();
    }

    public static void preCompile(){  // 预编译执行,性能高
        ExpressionCompiler compiler = new ExpressionCompiler("x + y");
        CompiledExpression exp = compiler.compile();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("x", 10);
        params.put("y", 20);
        Object result = MVEL.executeExpression(exp, params);
        System.out.println(result);
    }

    public static void explainScript(){  // 解释执行,性能低
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("a", "");
        params.put("b", 12);
        Object result = MVEL.eval("a==null||!b>10", params);
        System.out.println(result);
    }

    public static void scriptEngineManager(){ // 调动js解析器解析,性能较差
        String expr = "x+y*10";
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        engine.put("x", 10);
        engine.put("y", 10);
        try {
            System.out.println(engine.eval(expr));
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}