qlexpress 另外一个表达式引擎
qlexpress 是阿里开源的一个基于java 的脚本引擎,使用起来还是比较灵活的,以下是一个简单的使用
环境准备
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dalong.ex</groupId>
<artifactId>qlex-learnint</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<encoding>UTF-8</encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>QLExpress</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
</project>
- Application.java
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
/**
@author dalong
*/
public class Application {
public static void main(String[] args) throws Exception {
UserService userService =new UserService();
ExpressRunner runner = new ExpressRunner();
runner.addMacro("计算平均成绩", "(语文+数学+英语)/3.0");
runner.addMacro("是否优秀", "计算平均成绩>90");
IExpressContext<String, Object> context =new DefaultContext<String, Object>();
context.put("语文", 88);
context.put("数学", 99);
context.put("英语", 95);
runner.addFunctionOfServiceMethod("logout",userService,"logOut",new String[]{"String"},null);
runner.addFunctionOfClassMethod("取绝对值", Math.class.getName(), "abs",
new String[] { "double" }, null);
runner.addFunctionOfClassMethod("转换为大写", UserService.class.getName(),
"upper", new String[] { "String" }, null);
runner.addFunctionOfServiceMethod("打印", System.out, "println",new String[] { "String" }, null);
runner.addFunctionOfServiceMethod("contains", new UserService(), "anyContains",
new Class[] { String.class, String.class }, null);
String exp = "取绝对值(-100);转换为大写(\"hello world\");打印(\"你好吗?\");contains(\"helloworld\",\"aeiou\")";
Object result = runner.execute("是否优秀", context, null, false, false);
Object result2 = runner.execute(exp, context, null, false, false);
Object result3 = runner.execute("logout(\"demoapp\")", context, null, false, false);
System.out.println(result);
System.out.println(result2);
System.out.println(result3);
}
}
- UserService.java
/**
@author dalong
*/
public class UserService {
public static String token(String name,String password) {
return String.format("%s----%s",name,password);
}
public static String upper(String abc) {
return abc.toUpperCase();
}
public boolean anyContains(String str, String searchStr) {
char[] s = str.toCharArray();
for (char c : s) {
if (searchStr.contains(c+"")) {
return true;
}
}
return false;
}
}
说明
qlexpress 是一个不错的选择,但是从目前好多jvm 语言选择的脚本引擎来说js 越来越多了(可以的有nashorn ,rhino以及graalvm(更好)),个人比较推荐的
是js 引擎,因为很多时候提供类似的功能更多是为了系统的扩展,但是js 更加通用学习成本低,好多东西可以复用(集成起来typescript 会更加强大)