MVEL自定义函数重复掉用报错:duplicate function

MVEL自定义表达式重复掉用报错:duplicate function

原因:第一次调用时会将function缓存,再次调用时提示函数重复

方案:先将funciton放入缓存,再次调用时直接调用声明缓存中的函数

  • 自定义函数名,不要与参数名相同

示例代码:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MvelTest {
        
    @Test
    public void evalTest(){
        //表达式
        String roundup = "def roundup(num) { roundnum = null; if(num != null){ int roundnum = Math.round(num); } return roundnum; }";
        VariableResolverFactory functionFactory = new MapVariableResolverFactory();
        MVEL.eval(roundup, functionFactory);

        VariableResolverFactory resolverFactory = new MapVariableResolverFactory();
        resolverFactory.setNextFactory(functionFactory);
        Map map = new HashMap();
        map.put("A", new BigDecimal(2.33));
        map.put("B", new BigDecimal(4));
        String exp = "roundup(A*B)";
        System.out.println(MVEL.eval(exp, map, resolverFactory));

        System.out.println("------------");

        VariableResolverFactory resolverFactory2 = new MapVariableResolverFactory();
        resolverFactory2.setNextFactory(functionFactory);
        Map map2 = new HashMap();
        map2.put("A", new BigDecimal(3.33));
        map2.put("B", new BigDecimal(2));
        System.out.println(MVEL.eval(exp, map2, resolverFactory2));
    }
}

错误代码示例

向缓存中加入roundup函数

第一次执行成功

再次调用再次向缓存中加入roundup函数

VariableResolverFactory中存在函数抛出异常

MVEL自定义函数重复掉用报错:duplicate function_第1张图片

MVEL自定义函数重复掉用报错:duplicate function_第2张图片

MVEL自定义函数重复掉用报错:duplicate function_第3张图片

你可能感兴趣的:(java)