zoukankan      html  css  js  c++  java
  • 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<String, Object> map = new HashMap<String, Object>();
            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<String, Object> map2 = new HashMap<String, Object>();
            map2.put("A", new BigDecimal(3.33));
            map2.put("B", new BigDecimal(2));
            System.out.println(MVEL.eval(exp, map2, resolverFactory2));
        }
    }
    

    错误代码示例

    向缓存中加入roundup函数

    第一次执行成功

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

    VariableResolverFactory中存在函数抛出异常

  • 相关阅读:
    poj--2031--Building a Space Station(prime)
    nyoj--364--田忌赛马(贪心)
    nyoj--496--巡回赛(拓扑排序)
    nyoj--1100--WAJUEJI which home strong!(bfs)
    hdoj--5625--Clarke and chemistry(枚举)
    poj--1753--Flip Game(dfs好题)
    poj--1101--The Game(bfs)
    冒泡排序
    php常见错误
    php乱码
  • 原文地址:https://www.cnblogs.com/PoetryAndYou/p/15747970.html
Copyright © 2011-2022 走看看