前提:我用的jar包是:ik-expression-2.1.2.jar,一定要注意版本不同的jar,对应的xml的名称也不一样!!!!
1.创建xml:名称为:IKExpression.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<function-configuration>
<!-- 系统函数默认配置 -->
<bean class="org.wltea.expression.function.SystemFunctions">
<function name="CONTAINS" method="contains">
<parameter-type>java.lang.String</parameter-type>
<parameter-type>java.lang.String</parameter-type>
</function>
<function name="STARTSWITH" method="startsWith">
<parameter-type>java.lang.String</parameter-type>
<parameter-type>java.lang.String</parameter-type>
</function>
<function name="ENDSWITH" method="endsWith">
<parameter-type>java.lang.String</parameter-type>
<parameter-type>java.lang.String</parameter-type>
</function>
<function name="CALCDATE" method="calcDate">
<parameter-type>java.util.Date</parameter-type>
<parameter-type>int</parameter-type>
<parameter-type>int</parameter-type>
<parameter-type>int</parameter-type>
<parameter-type>int</parameter-type>
<parameter-type>int</parameter-type>
<parameter-type>int</parameter-type>
</function>
<function name="SYSDATE" method="sysDate" />
<function name="DAYEQUALS" method="dayEquals">
<parameter-type>java.util.Date</parameter-type>
<parameter-type>java.util.Date</parameter-type>
</function>
</bean>
<!-- 自定义函数配置-->
<bean class="com.cn.data.util.Functions">
<function name="TestDemo" method="test">
<parameter-type>java.lang.String</parameter-type>
</function>
</bean>
</function-configuration>
2.创建自定义的Functions类:
package com.cn.data.util;
public class Functions {
public String test(String name) {
return "hi, " + name;
}
}
3.在代码段里实现:
第一种:
import org.wltea.expression.ExpressionEvaluator;
······
······
String expression="$TestDemo(\"小明\")";
Object result =ExpressionEvaluator.evaluate(expression);
第二种:
import org.wltea.expression.ExpressionEvaluator;
import org.wltea.expression.datameta.Variable;
···········
···········
String expression = "$TestDemo(name)";
List<Variable> varialbes = new LinkedList<Variable>();
varialbes.add(Variable.createVariable("name", "小明"));
Object result = ExpressionEvaluator.evaluate(expression, varialbes);
注意:千万不要写在service里再调用ik表达式!!!包要看仔细引对!!!
二、可以传list参数,下面的例子是取List里的最大值,步骤如下:
1.xml文件:
<bean class="com.cn.data.util.Functions">
<function name="Max" method="max">
<parameter-type>java.util.List</parameter-type>
</function>
</bean>
2.Fuction里的方法:
/**
* 最大值
* 页面输入格式:$Max(参数1#参数2#参数3#参数4)
* @param oj
* @return
*/
public String max(List list) {
Double num1=Double.parseDouble(list.get(0).toString());
Object result=new Object();
result = num1;
for(Object num :list) {
if(Double.parseDouble(num.toString())>num1) {
num1 = Double.parseDouble(num.toString());
result=num;
}
}
return result.toString();
}
4.调用代码段里写:
import org.wltea.expression.ExpressionEvaluator;
······
······
String expression="$Max(1#2#3)";
Object result =ExpressionEvaluator.evaluate(expression);
给大家一份特别有用的参考的文档:https://linliangyi2007.iteye.com/blog/337069