Java平台的内嵌脚本支持JSR223以及commons-jexl简单使用

前言

JDK6加入对JSR233-Java平台脚本的支持(JSR 223: Scripting for the Java Platform?),可以用来在Java程序中调用脚本。

?

1.支持的脚本类型

?

import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import java.util.List;

public class TestSupport {
    public static void main(String[] args) {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        List<ScriptEngineFactory> engineFactories = scriptEngineManager.getEngineFactories();
        if (engineFactories.size() == 0) {
            System.out.println("本JVM尚不支持任何脚本引擎");
            return;
        }

        System.out.println("本JVM支持的脚本引擎有:");
        for (ScriptEngineFactory engineFactory : engineFactories) {
            System.out.println("引擎名称:" + engineFactory.getEngineName());
            System.out.println("\t可被ScriptEngineManager识别的名称:" + engineFactory.getNames());
            System.out.println("\t该引擎支持的脚本语言名称:" + engineFactory.getLanguageName());
            System.out.println("\t是否线程安全:" + engineFactory.getParameter("THREADING"));
        }
    }
}

?

?

?

2.DEMO

?

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class TestScript1 {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("javascript");
        String exp = "c=a+b;if(c<0){‘负数‘}else if(c==0){‘零‘}else{c};";
        scriptEngine.put("a", Math.random()*(-10));
        scriptEngine.put("b", Math.random()*10);
        Object result = scriptEngine.eval(exp);
        System.out.println(exp + " === " + result);
    }
}

?

?

2.commons-jexl

Apache commons-jexl是基于JSR233的扩展库,只需添加依赖就可以使用。

(1)Maven Dependency

?

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-jexl</artifactId>
    <version>2.1.1</version>
</dependency>

?

?

(2)DEMO

import java.util.Date;

public class Pojo {
    private String str;
    private Integer inte;
    private Boolean bool;
    private Date date;

    public Pojo(String str, Integer inte, Boolean bool, Date date) {
        this.str = str;
        this.inte = inte;
        this.bool = bool;
        this.date = date;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public Integer getInte() {
        return inte;
    }

    public void setInte(Integer inte) {
        this.inte = inte;
    }

    public Boolean getBool() {
        return bool;
    }

    public void setBool(Boolean bool) {
        this.bool = bool;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

?

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class TestJexl {
    public static void main(String[] args) {
        /**
         * 新建或取回JexlEngine
         */

        JexlEngine jexl = new JexlEngine();

        /**
         * 初始化一个JexlContext对象,它代表一个执行JEXL表达式的上下文环境
         */
        JexlContext context = new MapContext();

        // 准备并设置JEXL表达式上下文环境
        Pojo pojo = new Pojo("Pojo", 123, true, new Date());
        List<String> list = Lists.newArrayList("a1", "", "c3");
        Map<String, Object> map = Maps.newHashMap();
        map.put("key", "value");
        map.put("pojo", pojo);

        context.set("pojo", pojo);
        context.set("list", list);
        context.set("map", map);

        // 准备表达式
        List<String> jexlExps = Lists.newArrayList("pojo.str", "pojo.inte", "pojo.bool", "pojo.date"
                , "size(list)", "list[0].length()", "list[0].toUpperCase()", "empty(list[1])"
                , "map[‘key‘]", "map[‘pojo‘].str");

        // 执行表达式
        for (String jexlExp : jexlExps) {
            // 建立表达式对象 Create expression object
            Expression expression = jexl.createExpression(jexlExp);
            // 传入上下文环境并执行
            Object obj = expression.evaluate(context);
            System.out.println(expression.getExpression() + " = " + obj);
        }

    }
}

?

?

?

?

?

?

?

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。